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.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num = "3456237490", target = 9191
Output: []
void backtracking(const string& num, int target, string path, vector<string>& res, int pos, long val, long pre_multi) {
if (pos == num.length()) {
if (val == target)
res.emplace_back(path);
return;
}
for (int i = pos; i < num.length(); ++i) {
// Skip a number starting with '0' digit
if (i != pos && num[pos] == '0') break;
string cur_num = num.substr(pos, i + 1 - pos);
long cur = stol(cur_num);
if (pos == 0)
backtracking(num, target, cur_num, res, i + 1, cur, cur);
else {
backtracking(num, target, path + "+" + cur_num, res, i + 1, val + cur, cur);
backtracking(num, target, path + "-" + cur_num, res, i + 1, val - cur, -cur);
backtracking(num, target, path + "*" + cur_num, res, i + 1, val - pre_multi + pre_multi * cur, pre_multi * cur);
}
}
}
vector<string> addOperators(string num, int target) { // time: O(4^n); space: O(n)
if (num.empty()) return {};
vector<string> res;
backtracking(num, target, "", res, 0, 0, 0);
return res;
}
Last updated
Was this helpful?