首页 > 其他 > 详细

leetcode [241] - Different Ways to Add Parentheses

时间:2019-05-21 16:29:51      阅读:112      评论:0      收藏:0      [点我收藏+]

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

 




leetcode [241] - Different Ways to Add Parentheses

原文:https://www.cnblogs.com/lpomeloz/p/10900344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!