/*
Given a string that contains only digits 0-9 and a target value, print out all possibilities to add binary operators + and -
between the digits so they evaluate to the target value.
"123", 6 -> ["1+2+3"]
"105", 5 -> ["10-5"]
*/
List res;
public List addOperators(String num, int target) {
res = new ArrayList();
helper(num, target, "", 0, 0);
return res;
}
private void helper(String num, int target, String tmp, long currRes, long prevNum){
if(currRes == target && num.length() == 0){
String exp = new String(tmp);
res.add(exp);
return;
}
for(int i = 1; i 1 && currStr.charAt(0) == '0'){
return;
}
long currNum = Long.parseLong(currStr);
String next = num.substring(i);
if(tmp.length() != 0){
helper(next, target, tmp+"+"+currNum, currRes + currNum, currNum);
helper(next, target, tmp+"-"+currNum, currRes - currNum, -currNum);
} else {
helper(next, target, currStr, currNum, currNum);
}
}