[LeetCode] Expression Add Operators
This post shares a very nice solution, which is rewritten below.
1 class Solution { 2 public: 3 vector<string> addOperators(string num, int target) { 4 int n = num.length(); 5 if (!n) return {}; 6 vector<string> ans; 7 for (int i = 1; i <= n; i++) { 8 string s = num.substr(0, i); 9 long v = stol(s); 10 if (s != to_string(v)) continue; 11 add(ans, num, target, s, i, v, v, '$'); 12 } 13 return ans; 14 } 15 private: 16 void add(vector<string>& ans, string& num, int target, string s, int i, long v, long pv, char op) { 17 int n = num.length(); 18 if (i == n && v == target) 19 ans.push_back(s); 20 else { 21 for (int p = i + 1; p <= n; p++) { 22 string t = num.substr(i, p - i); 23 long d = stol(t); 24 if (t != to_string(d)) continue; 25 add(ans, num, target, s + '+' + t, p, v + d, d, '+'); 26 add(ans, num, target, s + '-' + t, p, v - d, d, '-'); 27 add(ans, num, target, s + '*' + t, p, (op == '+') ? v - pv + pv * d : ((op == '-') ? v + pv - pv * d: pv * d), pv * d, op); 28 } 29 } 30 } 31 };