14-line c++ solution


  • 14
    M
    class Solution {
    public:
        
        vector<int> diffWaysToCompute(string input) {
            vector<int> ans;
            bool pureNum=true;
            for (int i=0; i<input.length(); i++) 
                if (input[i]<'0' || input[i]>'9') {
                    pureNum=false;
                    vector<int> L=diffWaysToCompute(input.substr(0, i)), R=diffWaysToCompute(input.substr(i+1, input.length()-i-1));
                    for (auto l : L)
                        for (auto r : R)
                            if (input[i]=='+') ans.push_back(l+r);
                            else if (input[i]=='-') ans.push_back(l-r);
                            else if (input[i]=='*') ans.push_back(l*r);
                }
            
            if (pureNum)
                ans.push_back(atoi(input.c_str()));
            return ans;
        }
    };

  • 1
    K

    There is a bug in your codes. I think c should be input[i].
    But I still give you a upvote since your codes are very simple and clear.


  • 0
    M

    thanks! yes, the char c should be set to input[I]. I made that change after running the code. modified. regards.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.