|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<string> addOperators(string num, int target) { |
| 4 | + vector<string> result; |
| 5 | + if (num.size() == 0) return result; |
| 6 | + findSolution(num, target, result, "", 0, 0, 0, ' '); |
| 7 | + return result; |
| 8 | + } |
| 9 | + |
| 10 | + //DFS algorithm |
| 11 | + void findSolution(const string &num, const int target, |
| 12 | + vector<string>& result, |
| 13 | + string solution, |
| 14 | + int idx, |
| 15 | + long long val, |
| 16 | + long long prev, |
| 17 | + char preop ) |
| 18 | + { |
| 19 | + |
| 20 | + if (target == val && idx == num.size()){ |
| 21 | + result.push_back(solution); |
| 22 | + return; |
| 23 | + } |
| 24 | + if (idx == num.size()) return; |
| 25 | + |
| 26 | + string n; |
| 27 | + long long v=0; |
| 28 | + for(int i=idx; i<num.size(); i++) { |
| 29 | + //get rid of the number which start by "0" |
| 30 | + //e.g. "05" is not the case. |
| 31 | + if (n=="0") return; |
| 32 | + |
| 33 | + n = n + num[i]; |
| 34 | + v = v*10 + num[i]-'0'; |
| 35 | + |
| 36 | + if (solution.size()==0){ |
| 37 | + findSolution(num, target, result, n, i+1, v, 0, ' '); |
| 38 | + }else{ |
| 39 | + // '+' or '-' needn't to adjust the priority |
| 40 | + findSolution(num, target, result, solution + '+' + n, i+1, val+v, v, '+'); |
| 41 | + findSolution(num, target, result, solution + '-' + n, i+1, val-v, v, '-'); |
| 42 | + if (preop=='+') { |
| 43 | + findSolution(num, target, result, solution + '*' + n, i+1, (val-prev)+prev*v, prev*v, preop); |
| 44 | + }else if (preop=='-'){ |
| 45 | + findSolution(num, target, result, solution + '*' + n, i+1, (val+prev)-prev*v, prev*v, preop); |
| 46 | + }else { |
| 47 | + findSolution(num, target, result, solution + '*' + n, i+1, val*v, v, '*'); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | +}; |
0 commit comments