Extreme concise c++ solution


  • 7
    G
    class Solution {
    public:
        vector<int> diffWaysToCompute(string input) {
            if(input.size() ==0) return {};
            vector<int> result;
            for(int i = 0; i < input.size(); i++)
            {
                if(input[i]!='+' &&input[i]!= '-' &&input[i]!= '*') continue;
                auto vec1 = diffWaysToCompute(input.substr(0, i));
                auto vec2 = diffWaysToCompute(input.substr(i+1));
                for(auto val1: vec1)
                {
                    for(auto val2: vec2)
                    {
                        if(input[i]=='+') result.push_back(val1+ val2);
                        else if(input[i]=='-') result.push_back(val1 - val2);
                        else if(input[i]== '*') result.push_back(val1 * val2);
                    }
                }
            }
            return result.empty()?vector<int>{stoi(input)}:result;
        }
    };

  • 0

    @goodliar Actually you can just replace rec1 and rec2 with its invoking function which can be then called concise. Then you might want to ask "isn't the second function will be invoked lots of times", but actually the compiler will optimise it automatically using a temporary to store it. Anyway, your code is quite impressive.


  • 0
    5

    @LHearen your method is quit impressive


  • 0
    A

    @LHearen said in Extreme concise c++ solution:

    invoking function

    I don't get what do you mean by invoking function? Would you mind explain a bit?


Log in to reply
 

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