public class Solution {
public List<String> addOperators(String num, int target) {
List<String> res = new LinkedList<>();
helper(res, num, target, "", 0, 0);
return res;
}
private void helper(List<String> res, String num, int target, String temp, long curRes, long prevNum) {
if (curRes == target && num.length() == 0) {
res.add(new String(temp));
return;
}
for (int i = 1; i <= num.length(); i++) {
String curStr = num.substring(0, i);
if (curStr.length() > 1 && curStr.charAt(0) == '0') {
return;
}
long curNum = Long.valueOf(curStr);
String nextNum = num.substring(i);
if (temp.length() != 0) {
helper(res, nextNum, target, temp + '*' + curStr, curRes - prevNum + prevNum * curNum, prevNum * curNum);
helper(res, nextNum, target, temp + '+' + curStr, curRes + curNum, curNum);
helper(res, nextNum, target, temp + '-' + curStr, curRes - curNum, -curNum);
} else {
helper(res, nextNum, target, curStr, curNum, curNum);
}
}
}
}