@@ -23,39 +23,36 @@ class Solution {
2323 }
2424
2525 void addOperatorsDFS (const string& num, const int & target, const int & pos,
26- const int & operand1, const int & operand2, vector<string> *expr,
27- vector<string> *result) {
28- if (pos == num.length ()) {
29- if (operand1 + operand2 == target) {
30- result->emplace_back (move (join (*expr)));
31- }
32- return ;
33- }
26+ const int & operand1, const int & operand2,
27+ vector<string> *expr, vector<string> *result) {
28+ if (pos == num.length () && operand1 + operand2 == target) {
29+ result->emplace_back (move (join (*expr)));
30+ } else {
31+ int val = 0 ;
32+ string val_str;
33+ for (int i = pos; i < num.length (); ++i) {
34+ val = val * 10 + num[i] - ' 0' ;
35+ val_str.push_back (num[i]);
36+ // Avoid overflow and "00...".
37+ if (to_string (val) != val_str) {
38+ break ;
39+ }
3440
35- int val = 0 ;
36- string val_str;
37- for (int i = pos; i < num.length (); ++i) {
38- val = val * 10 + num[i] - ' 0' ;
39- val_str.push_back (num[i]);
40- // Avoid overflow and "00...".
41- if (to_string (val) != val_str) {
42- break ;
43- }
44-
45- // Case '+':
46- expr->emplace_back (" +" + val_str);
47- addOperatorsDFS (num, target, i + 1 , operand1 + operand2, val, expr, result);
48- expr->pop_back ();
49-
50- // Case '-':
51- expr->emplace_back (" -" + val_str);
52- addOperatorsDFS (num, target, i + 1 , operand1 + operand2, -val, expr, result);
53- expr->pop_back ();
41+ // Case '+':
42+ expr->emplace_back (" +" + val_str);
43+ addOperatorsDFS (num, target, i + 1 , operand1 + operand2, val, expr, result);
44+ expr->pop_back ();
5445
55- // Case '*':
56- expr->emplace_back (" *" + val_str);
57- addOperatorsDFS (num, target, i + 1 , operand1, operand2 * val, expr, result);
58- expr->pop_back ();
46+ // Case '-':
47+ expr->emplace_back (" -" + val_str);
48+ addOperatorsDFS (num, target, i + 1 , operand1 + operand2, -val, expr, result);
49+ expr->pop_back ();
50+
51+ // Case '*':
52+ expr->emplace_back (" *" + val_str);
53+ addOperatorsDFS (num, target, i + 1 , operand1, operand2 * val, expr, result);
54+ expr->pop_back ();
55+ }
5956 }
6057 }
6158
0 commit comments