Given a string that contains only digits 0-9
and a target value, return all possibilities to add binaryoperators (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: []
思路:
我们这里参看了LeetCode提供的解答:here。当然,仅仅靠上面的解答完成的CPP程序最后一个实例会超时,所以我们做了一些改进,主要是在traceback的时候,我们直接用赋值的方式替换了“还原的方式”。
class Solution {
public:
vector addOperators(string num, int target) {
this->num = num;
this->target = target;
recurse(0, 0, 0, 0, string());
return res;
}
private:
vector res;
string num;
int target;
void recurse(int index, long pre_num, long current_num, long val, string candidate) {
if (index == num.size()) {
if (val == target && current_num == 0) res.push_back(candidate.substr(1));
return;
}
current_num = current_num * 10 + num[index] - '0';
string curr_str = to_string(current_num);
if (current_num > 0) recurse(index + 1, pre_num, current_num, val, candidate);
int n = candidate.size();
candidate.push_back('+'); candidate += curr_str;
recurse(index + 1, current_num, 0, val + current_num, candidate);
if (n > 0) {
candidate[n] = '-';
recurse(index + 1, -current_num, 0, val - current_num, candidate);
candidate[n] = '*';
recurse(index + 1, current_num * pre_num, 0, val - pre_num + pre_num * current_num, candidate);
}
}
};