leetcode241

来源:互联网 发布:什么是数据票和进项票 编辑:程序博客网 时间:2024/06/05 16:23

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 *.


(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

f分治题,以每个算数符为分界,分成左右两个部分,分别算出左右的解集,然后合并。

例如:

2*3-4*5

第一次*为分界限:2,3-4*5

2不能往下再分,3-4*5以每个运算符分界又可以分成 3,-,4*5  和 3-4,*,5  结果为-17和-5

所以[2], [-17,-5]组合变成[-34,-10]。


第二次以-分割:-14

第三次*分割:[-2,2]  * [5] = -10,10



class Solution {
public:
    int compute(char ch,int a,int b)
    {
        switch(ch)
        {
            case'+':return (a+b);
            case'-':return (a-b);
            case'*':return (a*b);
        }
        return 0;
    }
    vector<int> diffWaysToCompute(string input) {
    vector<int> res;
    bool flag =false; //代表有无运算符
        for(int i=0;i<input.size();i++)
        {
            char ch = input[i];
            if(ch=='+'||ch=='-'||ch=='*')
            {
                flag = true;
                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++)
                    {
                        res.push_back(compute(ch,left[j],right[k]));
                    }
                }
            }
        }
        if(!flag) //没有运算符,只剩一个数的时候
        {
            stringstream ss(input);
            int n;
            ss>>n;
            res.push_back(n);
        }
        return res;
    }
};