LeetCode 241. Different Ways to Add Parentheses

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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".

((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]

 

思路:

1.自己看到题的时候的思路:把运算符和两边数字括号后看成一个整体,递归完成括号化.......这样子自己不知道怎么写代码

2.参考Gcdofree的方法:分治法,递归完成,这个思路比较好

3.动态规划:这个现在还没懂,等以后来补充

 

代码:C++ 思路2

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> solution;
        for (int i = 0; i < input.size(); i++) {
            if (input[i] == + || input[i] == - || input[i] == *) {
                vector<int> left = diffWaysToCompute(input.substr(0,i));
                vector<int> right = diffWaysToCompute(input.substr(i + 1));
                for (int j = 0; j < left.size(); j++) {
                    for (int k = 0; k < right.size(); k++) {
                        if (input[i] == +)
                            solution.push_back(left[j] + right[k]);
                        else if (input[i] == -)
                            solution.push_back(left[j] - right[k]);
                        else
                            solution.push_back(left[j] * right[k]);
                    }
                }
            }
        }
        if (solution.empty())
            solution.push_back(stoi(input));
        return solution;
    }
};

 

以上是关于LeetCode 241. Different Ways to Add Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 241. Different Ways to Add Parentheses

leetcode 241. Different Ways to Add Parentheses (Python版)

leetcode 241. Different Ways to Add Parentheses

[LeetCode] 241. Different Ways to Add Parentheses

leetcode [241]Different Ways to Add Parentheses

LeetCode-241 Different Ways to Add Parentheses