LeetCode 241. Different Ways to Add Parentheses

2020-04-08 11:18:17 浏览数 (1)

题目

递归,分治,暴力跑就可以了

代码语言:javascript复制
class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        
        vector<int> ans;
        if(input=="")
            return ans;
        int tag=0;
        for(int i=0;i<input.length();i  )
        {
            if(!(input[i]>='0'&&input[i]<='9'))
            {
                tag=1;
                vector<int> ans1 = diffWaysToCompute(input.substr(0,i));
                vector<int> ans2 = diffWaysToCompute(input.substr(i 1,input.length()-i-1));
                
                for(int j=0;j<ans1.size();j  )
                {
                    for(int k=0;k<ans2.size();k  )
                    {
                        if(input[i]==' ')
                            ans.push_back(ans1[j] ans2[k]);
                        else if(input[i]=='-')
                            ans.push_back(ans1[j]-ans2[k]);
                        else
                            ans.push_back(ans1[j]*ans2[k]);
                    }
                }
            }
        }
        
        if(!tag)
        {
            int num=0;
            for(int i=0;i<input.length();i  )
            {
                num*=10;
                num =input[i]-'0';
            }
            ans.push_back(num);
        }
        
        return ans;
        
    }
};

0 人点赞