Expression Add Operators

https://leetcode.com/problems/expression-add-operators/

class Solution {
public:
    vector<string> addOperators(string num, int target) {

        vector<string> rst;
        if(num.length() == 0)
        {
            return rst;
        }

        string path;
        dfs(rst, path, num, target, 0, 0, 0);

        return rst;
    }

    void dfs(vector<string>& rst, string path, const string& num, int target, int pos, long eval, long multied)
    {
        if(pos >= num.length())
        {
            if(eval == target)
            {
                rst.push_back(path);
            }
            return;
        }

        for(int i = pos; i < num.length(); i++)
        {
            if(i != pos && num[pos] == '0')
            {
                break;
            }
            long cur = stol(num.substr(pos, i-pos+1));

            if(pos == 0)
            {
                dfs(rst, num.substr(pos, i-pos+1), num, target, i+1, cur, cur);
            }
            else
            {
                dfs(rst, path + "+" + num.substr(pos, i-pos+1), num, target, i+1, eval + cur, cur);
                dfs(rst, path + "-" + num.substr(pos, i-pos+1), num, target, i+1, eval - cur, cur*(-1));
                dfs(rst, path + "*" + num.substr(pos, i-pos+1), num, target, i+1, eval - multied + cur * multied, cur * multied);
            }

        }


    }
};

results matching ""

    No results matching ""