282. 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 -> []

 1 class Solution {
 2 public:
 3     vector<string> addOperators(string num, int target) {
 4 
 5         vector<string> res;
 6         if (num.size() == 0)
 7             return res;
 8 
 9         DFS(num, target, 0, "", res, 0, 0);
10         return res;
11     }
12 
13     void DFS(string& num, int& target, int cur, string path,
14             vector<string>& res, long long diff, long long sum) {
15 
16         if (cur == int(num.size()) && sum == target) {
17             res.push_back(path);
18             return;
19         }
20         for (size_t i = cur; i < num.size(); i++) {
21             string curStr = num.substr(cur, i - cur + 1);
22             if (curStr.size() > 1 && curStr[0] == '0')
23                 return;
24             long  curVal = atol(curStr.c_str());
25             if (cur > 0) {
26                 DFS(num, target, i + 1, path + '+' + curStr, res, curVal,
27                         sum + curVal);
28                 DFS(num, target, i + 1, path + '-' + curStr, res, -curVal,
29                         sum - curVal);
30                 DFS(num, target, i + 1, path + '*' + curStr, res, diff * curVal,
31                         sum - diff + diff * curVal);
32             } else {
33                 DFS(num, target, i + 1, path + curStr, res, curVal,
34                         sum + curVal);
35             }
36         }
37 
38     }
39 };

 

posted @ 2015-12-24 17:17  wxquare  阅读(280)  评论(0编辑  收藏  举报