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 -> []
题目是一道比较明显的回溯题目,主要边界点有:
1、String格式转为数溢出问题,采用long解决
2、连0开头的数比如001是无效的问题
因为有乘法,所以用到了一个技巧,从而可以在递归中解决乘法。
比如一个式子 1 + 2 * 3,我们在递归回溯的时候,先计算的是 1 + 2 = 3记为 val,而把 2 记为 mult,也就是下一轮中如果有乘法,那么要拿 mult作为一个乘数 ,下一轮出现一个乘法,那么val - mult 就相当于回退上一轮的加法操作,而 mult * cur 就是把上一轮的乘数乘到本轮,即本轮求出的结果是 val - mult + mult * cur. 同样对于减法和乘法,mult的值要进行相应改变。
回溯的思路比较简单,就是每一轮从一个位置开始,选一个位置加入 +,-,*进行递归,但是乘法的trick不容易想到。
代码如下:
public class Solution {
private String num;
public List<String> addOperators(String num, int target) {
List<String> result = new ArrayList<>();
if (num == null || num.length() == 0) return result;
this.num = num;
helper(result,target,"",0,0,0);
return result;
}
private void helper(List<String> res, int target, String path, int pos, long val, long mult) {
if (pos == num.length()) {
if (target == val) {
res.add(path);
return;
}
}
for (int i = pos;i<num.length();i++) {
if (i != pos && num.charAt(pos) == '0') break;
long cur = Long.parseLong(num.substring(pos,i + 1));
if (pos == 0)
helper(res,target,path + cur,i + 1,cur,cur);
else {
helper(res,target,path + "+" + cur,i + 1,val + cur,cur);
helper(res,target,path + "-" + cur,i + 1,val - cur,-cur);
helper(res,target,path +"*" + cur,i + 1,val - mult + mult * cur,mult * cur);
}
}
}
}