题目:

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

 

posted on 2016-02-02 18:21  gavinXing  阅读(173)  评论(0编辑  收藏  举报