1. 程式人生 > >Leetcode|Different Ways to Add Parentheses

Leetcode|Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1
Input: “2-1-1”.

((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]

Example 2
Input: “2*3-4*5”

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

這題不是很好想,通過率可不低啊。
解法1:回溯法列出所有括號組合,分別用棧來計算。
有點複雜。這可以當做兩個題目來做了。
解法2:和 Unique Binary Search Trees II 類似。分治的思想。
難點是要想到用符號當做分界點。
用遞迴實現。非遞迴還沒想好。

class Solution {
public:
    vector<int> diffWaysToCompute(string
input) { vector<int> res; int data=0; int i; for(i=0;i<input.length()&&isdigit(input[i]);i++){ data=data*10+input[i]-'0'; } if(i==input.length()){ res.push_back(data); return res; } vector<int> left,right; for(int
i=0;i<input.length();i++){ if(isdigit(input[i])) continue; left=diffWaysToCompute(input.substr(0,i)); right=diffWaysToCompute(input.substr(i+1,input.length()-1-i)); for(int l=0;l<left.size();l++){ for(int r=0;r<right.size();r++){ res.push_back(calculate(left[l],right[r],input[i])); } } } return res; } private: int calculate(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; } return 1; } };