Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

Examples:

"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        int n = num.length();
        vector<string> result;
        visit(num, n, 0, 0, 0, "",  target, result);

        return result;
    }
private:
    void visit(string &num, int n, int pos, long cur, long prev, string buf, int target, vector<string> &result)
    {
        if (pos == n)
        {
            if (cur == target)
            {
                result.push_back(buf);
            }

            return;
        }

        for (int i = pos; i < n; i++)
        {
            if (num[pos] == '0' && i > pos)
            {
                break;
            }
            string temp = num.substr(pos, i-pos+1);
            long val = stol(temp);
            if (pos == 0)
            {
                visit(num, n, i+1, val, val, temp, target, result);
            }
            else
            {
                visit(num, n, i+1, cur+val, val,  buf+"+"+temp, target, result);
                visit(num, n, i+1, cur-val, -val, buf+"-"+temp, target, result);
                visit(num, n, i+1, cur-prev+prev*val, prev*val, buf+"*"+temp, target, result);
            }
        }
    }
};


你可能感兴趣的:(Expression Add Operators)