Week Training: 241 Different Ways to Add Parentheses

来源:互联网 发布:幼儿园淘宝活动方案 编辑:程序博客网 时间:2024/06/05 21:00

As we are learning divide and conquer, a problem like this can help us understand well. It seems hard, since we don't know how long the string is, there might be lots of conditions. However, through the theory of divide and conquer and recursive, we can make the problem concise and easier to deal with. If we meet with operators like '+', '-' and '*', we just divide the string before and after it to 2 substrings, resursively doing the same thing to them. For each 2 substrings, we compute every element of it according to the operator. The principle of this method is easy-understanding, but of course too much loop used causes long run time, which is to be improved.

class Solution {public:    vector<int> diffWaysToCompute(string input) {        vector<int> result;        for(int i=0;i<input.size();i++){            char sym = input[i];            if(sym == '+'||sym == '-'||sym == '*'){                vector<int> r1 = diffWaysToCompute(input.substr(0,i));                vector<int> r2 = diffWaysToCompute(input.substr(i+1));                for(int j=0;j<r1.size();j++){                    for(int k=0;k<r2.size();k++){                        if(sym=='+')                            result.push_back(r1[j]+r2[k]);                        else if(sym=='-')                            result.push_back(r1[j]-r2[k]);                        else if(sym=='*')                            result.push_back(r1[j]*r2[k]);                    }                }            }        }        if(result.empty())            result.push_back(atoi(input.c_str()));        return result;    }};


0 0