Expression Add Operators

时间:2023-03-10 04:24:53
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.

Examples:

"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> [] 其实这题是很简单的,就是用DFS找出所有可能性,只是最最麻烦的是怎么处理前面部分是加减,后面部分是乘的情况。我本来是用逆波兰表达式来计算的,但是下面的解法更方便。
From: https://segmentfault.com/a/1190000003797204
 public class Solution {
public List<String> addOperators(String num, int target) {
List<String> resulstsList = new ArrayList<>();
helper(num, target, "", , , resulstsList);
return resulstsList;
} private void helper(String num, int target, String tmp, long currRes, long prevNum, List<String> res) {
if (currRes == target && num.length() == ) {
res.add(tmp);
return;
}
// 搜索所有可能的拆分情况
for (int i = ; i <= num.length(); i++) {
String currStr = num.substring(, i);
// 对于前导为0的数予以排除
if (currStr.length() > && currStr.charAt() == '') {
break;
}
// 得到当前截出的数
long currNum = Long.parseLong(currStr);
// 去掉当前的数,得到下一轮搜索用的字符串
String next = num.substring(i);
// 如果不是第一个字母时,可以加运算符,否则只加数字
if (tmp.length() != ) {
// 乘法
helper(next, target, tmp + "*" + currNum, (currRes - prevNum) + prevNum * currNum, prevNum * currNum, res);
// 加法
helper(next, target, tmp + "+" + currNum, currRes + currNum, currNum, res);
// 减法
helper(next, target, tmp + "-" + currNum, currRes - currNum, -currNum, res);
} else {
// 第一个数
helper(next, target, currStr, currNum, currNum, res);
}
}
}
}