[Leetcode] 241. Different Ways to Add Parentheses 解题报告

来源:互联网 发布:油田开发数据 编辑:程序博客网 时间:2024/06/05 05:25

题目

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]

思路

我开始的解法是回溯,发现代码实在是太复杂了,思路也不清晰。后来发现这道题目的正解是分治。不得不说,下面的分治策略的实现还是非常巧妙的:

题目的实质就是看运算符有多少种排列,然后每种排列都会对应一个最终结果。我们的做法是:对于每一个运算符,我们首先计算出它的左侧和右侧分别有多少种运算结果,然后把它们组合一下,再用该运算符进行运算获得结果。这里面会用到递归的实现方法,所以需要注意递归的边界(就是整个字符串就是一个数组,没有运算符)。

代码

class Solution {public:    vector<int> diffWaysToCompute(string input) {        return diffWaysToCompute(input, 0, input.length());    }private:    vector<int> diffWaysToCompute(string& input, int start, int end) {        vector<int> ret;        char c;        for(int i = start; i < end; ++i) {            c = input[i];            if(c == '+' || c == '-' || c == '*') {                vector<int> left = diffWaysToCompute(input, start, i);                vector<int> right = diffWaysToCompute(input, i + 1, end);                for(auto it1 = left.begin(); it1 != left.end(); ++it1) {                    for(auto it2 = right.begin(); it2 != right.end(); ++it2) {                        if(c == '+') {                            ret.push_back(*it1 + *it2);                        }                        else if(c == '-') {                            ret.push_back(*it1 - *it2);                        }                        else if(c == '*') {                            ret.push_back(*it1 * *it2);                        }                    }                }            }        }        if(ret.size() == 0) {            string substr = input.substr(start, end - start);            ret.push_back(atoi(substr.c_str()));        }        return ret;    }};