Tuesday, September 15, 2015

LeetCode [282] Expression Add Operators

282. Expression Add Operators
Hard

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.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"] 

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]

Example 3:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

Example 4:

Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]

Example 5:

Input: num = "3456237490", target = 9191
Output: []

 

Constraints:

  • 0 <= num.length <= 10
  • num only contain digits.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
typedef long long ll;
class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> ret;
        dfs(num, "", 0, 0, 0, ret, target);
        return ret;
    }

    void dfs(string num, string exp, int pos, ll curVal, ll preVal, vector<string>& ret, ll target)
    {
        if(pos == num.size() && curVal==target)
        {
            ret.push_back(exp);
        }
        else if(pos<num.size())
        {
            for(int i=pos; i<num.size(); ++i)
            {
                string v = num.substr(pos, i-pos+1);
                if(v.size()>1 && v[0]=='0') break;
                if(pos==0)
                {
                    dfs(num, v, i+1, stoll(v), stoll(v), ret, target);
                }
                else
                {
                    dfs(num, exp+"+"+v, i+1, curVal+stoll(v), stoll(v), ret, target);
                    dfs(num, exp+"-"+v, i+1, curVal-stoll(v), -stoll(v), ret, target);
                    dfs(num, exp+"*"+v, i+1, curVal-preVal+preVal*stoll(v), preVal*stoll(v), ret, target);
                }
                
            }
        }
    }
};

No comments:

Post a Comment