Answers for "finding all values of the mathematical expression"

C++
0

finding all values of the mathematical expression

#define vi vector<int>

vi evaluate_expressions(unordered_map<string, vi> &umap, string s){
    if(umap.find(s) != umap.end()) return umap[s];
    
    vi res = {};

    if(s.find('+') == string::npos and s.find('-') == string::npos and s.find('*') == string::npos)
        res.push_back(stoi(s));

    else{
        for(size_t i = 0; i < s.size(); ++i){
            char c = s[i];
            if(c < 48){
                vi left = evaluate_expressions(umap, s.substr(0,i));
                vi right  = evaluate_expressions(umap, s.substr(i+1));
                for(int &l: left){
                    for(int &r: right){
                        if(c == '+')
                            res.push_back(l+r);
                        else if(c == '-')
                            res.push_back(l-r);
                        else if(c == '*')
                            res.push_back(l*r);
                    }
                }
            }
        }
    }
    umap[s] = res;
    return res;
}
Posted by: Guest on August-06-2021

Code answers related to "finding all values of the mathematical expression"

Browse Popular Code Answers by Language