leetcode题库之241

241/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]

中文翻译:给定一个由数字和运算符组成的字符串,通过对表达式进行不同组合(元素位置不变),计算出所有可能的结果。

这道题我开始尝试着自己解决,但是没解出来,我当时的想法是,将数字部分和符号部分分别提取出来,并对符号部分进行排列组合,每一种组合对应的是一种计算结果,但其中会出现重复的,再想办法把重复的去掉就可以,但是目前还没能实现。
我网上看了一下别人的解法,思路大概是这样的:

对输入的字符串进行从头到尾扫描,当遇到运算符时以该运算符为分界位置将字符串分成两个部分,并分别把这两部分作为形参传递给diffWaysToCompute函数(递归),最终会得到两个数值(result1,result2),再进行最后一步运算得到结果,把结果存储在动态数组中(result),进行下一次循环。循环结束,所有的可能结果都保存在result中了。
代码如下:

class Solution {
public:
//解题思想:将字符串分成两部分,第一部分结果=result1,第二部分结 果=result2,再相加得到最终的结果result
//主要是递归思想是递归
    vector<int> diffWaysToCompute(string input) 
    {
        vector<int> result;             //存储所有的可能结果
        int size = input.size();
        for (int i = 0; i < size; i++) {//确定分段的位置
            char cur = input[i];
            if (cur == '+' || cur == '-' || cur == '*') {
                vector<int> result1 = diffWaysToCompute(input.substr(0, i));
                vector<int> result2 = diffWaysToCompute(input.substr(i+1));
                for (auto n1 : result1) {//1、auto关键字(类型推导)2、range-based for 循环
                    for (auto n2 : result2) {
                        if (cur == '+')
                            result.push_back(n1 + n2);
                        else if (cur == '-')
                            result.push_back(n1 - n2);
                        else
                            result.push_back(n1 * n2);    
                    }
                }
            }
        }
        //当string仅为一个字符时
        if (result.empty())
            result.push_back(atoi(input.c_str()));
        return result;
    }
};

你可能感兴趣的:(leetcode题库之241)