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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class Solution { public: #ifndef ll #define ll long long #endif const static int maxn = 1e5 + 10; const static int maxm = 1e5 + 10; const static int INF = 0x3f3f3f3f; vector<string> ans; string op = "+-*"; void dfs(int step, ll cur_sum, ll last_sum, string &cur, int &target, string &num) { if (step == num.length()) { if (cur_sum == target) ans.emplace_back(cur); return; } int len = cur.size(); if (step > 0) cur.push_back('+'); int index = cur.size() - 1; ll val = 0; for (int i = step; i < num.size(); ++i) { val = val * 10 + (num[i] - '0'); cur.push_back(num[i]); if (step == 0) { dfs(i + 1, cur_sum + val, val, cur, target, num); } else { cur[index] = '+'; dfs(i + 1, cur_sum + val, val, cur, target, num); cur[index] = '-'; dfs(i + 1, cur_sum - val, -val, cur, target, num); cur[index] = '*'; dfs(i + 1, cur_sum - last_sum + last_sum * val, last_sum * val, cur, target, num); } if (i == step && num[i] == '0') { while (step + 1 < num.size() && num[step + 1] == num[step]) step++; break; } } cur.resize(len); } vector<string> addOperators(string num, int target) { string cur; dfs(0, 0, 0, cur, target, num); return ans; } };
|