题目描述:
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: []
/***
* @param num remaining string of numbers
* @param target target value
* @param curExp current expression
* @param curRes result of current expression
* @param preNum previous value (for multiply)
* a + b - c * d + preNum # cur , # can take +/-/*, use recursion to solve it
* curExp = "a+b-c*d+preNum"
*/
class Solution {
public:
void addOperatorsDFS(string num, int target, long long preNum, long long curRes, string curExp, vector<string> &res) {
if (num.size() == 0 && curRes == target) {
res.push_back(curExp);
}
for (int i = 1; i <= num.size(); ++i)
{
string cur = num.substr(0, i); //截取前i个字符作为运算数字
if (cur.size() > 1 && cur[0] == '0') return; //过滤首字符为0的数字
string remain = num.substr(i);
if (curExp.size() == 0) addOperatorsDFS(remain, target, stoll(cur), stoll(cur), cur, res);
else
{
addOperatorsDFS(remain, target, stoll(cur), curRes + stoll(cur), curExp + "+" + cur, res);
addOperatorsDFS(remain, target, -stoll(cur), curRes - stoll(cur), curExp + "-" + cur, res);
addOperatorsDFS(remain, target, preNum * stoll(cur), (curRes - preNum) + preNum * stoll(cur), curExp + "*" + cur, res);
}
}
}
vector<string> addOperators(string num, int target) {
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
};