leetcode [241] - 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"
Output: [0, 2]
Explanation: 
((2-1)-1) = 0 
(2-(1-1)) = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
  (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

题目大意:
对一个含有运算符'+''-''*'的运算表达式,通过添加‘( )’改变运算符优先级,计算所有可能的结果(包括重复的结果)。
理解:
采用递归和分而治之的方法,遍历整个字符串表达式,每遇到一个运算符,将它左边表达式作为一个,右边表达式作为另一个整体,依次递归计算。
函数返回值为当前表达式所有可能的计算结果,左部OPERATOR右部,即为所有可能结果值。

代码C++
class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> res;
        int len = input.length();
        for(int i=0;i<len;++i){
            if(input[i]=='+' ||input[i]=='-' || input[i]=='*'){
                auto res1 = diffWaysToCompute(input.substr(0,i));
                auto res2 = diffWaysToCompute(input.substr(i+1));
                for(auto left:res1){
                    for(auto right:res2){
                        switch(input[i]){
                            case '+':
                                res.push_back(left+right);
                                break;
                            case '-':
                                res.push_back(left-right);
                                break;
                            case '*':
                                res.push_back(left*right);
                                break;
                                
                        }
                    }
                }
            }
        }
        if(res.empty()){
             res.push_back(stoi(input));
        }
        return res;
    }
};

 




posted @ 2019-05-21 16:02  lpomeloz  阅读(114)  评论(0编辑  收藏  举报