Leetcode|Different Ways to Add Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_learns_to_rock/article/details/47357743

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;
    }
};

猜你喜欢

转载自blog.csdn.net/mike_learns_to_rock/article/details/47357743
今日推荐