ITPub博客

首页 > > > [LeetCode] Different Ways to Add Parentheses

[LeetCode] Different Ways to Add Parentheses

作者:Ruiyuan Li 时间:2015-08-17 00:00:00 0 删除 编辑

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.

解题思路;

这道题可以用递归的方法来做。对于一个输入字符串s,一次获得每个标点符号的左侧left和右侧right的值,然后两两组合成结果。

class Solution {
public:
    vector diffWaysToCompute(string input) {
        vector result;
        
        int len = input.length();
        if(len == 0){
            return result;
        }
        
        if(isInt(input)){
            result.push_back(std::stoi(input));
            return result;
        }
        
        for(int i=0; i'9'){
                vector leftResult = diffWaysToCompute(input.substr(0, i));
                vector rightResult = diffWaysToCompute(input.substr(i+1));
                for(int m = 0; m'9'){
                return false;
            }
        }
        return true;
    }
};


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825