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 -> []
Analysis
- 注意基本的backtracking方法一定要掌握!
- 这里处理乘法的方法非常巧妙,值得思考!
- for example, if you have a sequence of 12345 and you have proceeded to 1 + 2 + 3, now your eval is 6 right? If you want to add a between 3 and 4, you would take 3 as the digit to be multiplied, so you want to take it out from the existing eval. You have 1 + 2 + 3 4 and the eval now is (1 + 2 + 3) - 3 + (3 * 4). Hope this could help
- 注意如何处理开头是0的数字(数字多余一位且开头是0)
- 避免overflow,用long!
Code
public class Solution {
public List<String> addOperators(String num, int target) {
List<String> rst = new ArrayList<String>();
if (num==null || num.length()==0) return rst;
helper(rst, "", num, target, 0, 0, 0);
return rst;
}
private void helper(List<String> rst, String path, String num, int target, int pos, long eval, long multed){
if (pos==num.length()){
if (eval==target) rst.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(rst, path+cur, num, target, i+1, cur, cur);
}
else {
helper(rst, path+"+"+cur, num, target, i+1, eval+cur, cur);
helper(rst, path+"-"+cur, num, target, i+1, eval-cur, -cur);
helper(rst, path+"*"+cur, num, target, i+1, eval-multed+multed*cur, multed*cur);
}
}
}
}
Note
- long num = Long.parseLong(string)
Reference
Leetcode