本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti…
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 Example 1:
Input: “123” 6 Output: [“123”,“1+2+3”] Example 2:
Input: “232” 8 Output: [“23+2", "2+32”] Example 3:
Input: “105” 5 Output: [“1*0+5”,“10-5”] Example 4:
Input: “00” 0 Output: [“0+0”, “0-0”, “0*0”] Example 5:
Input: “3456237490”, 9191 Output: []
解法1:用DFS。 注意: 1)因为乘法优先级高,所以我们记下prevFactor,如果选择乘法,则将前面的prevFactor减去,再加上prevFactor与现在的number的乘积。 2) 用long long因为可能溢出。 3) 当输入为“00",同时target也为0时,输出可能是"00",应该将该可能性排除。
class Solution {
public:
/**
* @param num: a string contains only digits 0-9
* @param target: An integer
* @return: return all possibilities
*/
vector<string> addOperators(string &num, int target) {
int n = num.size();
if (n == 0) return vector<string>();
string sol;
dfs(num, 0, sol, 0, 0, target);
return sols;
}
private:
vector<string> sols;
void dfs(string &num, int index, string sol, long long sum, long long prevFactor, int target) {
int n = num.size();
if (index == n && target == sum) {
sols.push_back(sol);
return;
}
for (int i = index; i < n; ++i) {
string numStr = num.substr(index, i - index + 1);
long long number = stoll(numStr);
if (index == 0) {
dfs(num, i + 1, numStr, number, number, target);
} else {
dfs(num, i + 1, sol + '+' + numStr, sum + number, number, target);
dfs(num, i + 1, sol + '-' + numStr, sum - number, -number, target);
dfs(num, i + 1, sol + '*' + numStr, sum - prevFactor + prevFactor * number, prevFactor * number, target);
}
if (num[index] == '0') break; //to avoid "00"
}
}
};