class Solution {
/** for multiplication
cur-prev+prev*tmp, prev*tmp
2+3-4* 9, here I need to multiply by 4 which was the exact previous number
* now the 4 was alreaded insided the current evaluated expression in cur. So I need to deduct it from current to be able to multiply with
* the latest number
* The idea here is we iterate over the string, at every iteration, we add one digit to my latest number and try ot add '+', '-' '*'
* and evalute, this can be done with DFS. At every step, we create the number from my start index, and then evaluate with previous evaluation result
*/
public List<String> addOperators(String num, int target) {
if (num == null)
return null;
if (num.length() == 0)
return new ArrayList<String>();
List<String> result = new ArrayList<String>();
evaluateWithDFS(num, result, "", 0, 0, 0, target);
return result;
}
private void evaluateWithDFS(String num, List<String> result, String exprPath, int startIdx, long prevEvalResult, long prevNumber, int target) {
if (startIdx == num.length()) {
if (prevEvalResult == target)
result.add(exprPath);
return;
} else {
for (int i = startIdx; i<num.length(); i++) {
if (i != startIdx && num.charAt(startIdx)=='0') break;
String curNumStr = num.substring(startIdx, i+1);
long curNum = Long.parseLong(curNumStr);
if (startIdx == 0) {
evaluateWithDFS(num, result, curNumStr, i+1, curNum, curNum, target);
} else {
// Try '+' operator
String[] buildNewExprPath = {exprPath, "+", curNumStr};
evaluateWithDFS(num, result, BuildString(buildNewExprPath), i+1, prevEvalResult + curNum, curNum, target);
// Try '-' operator
String[] buildNewExprPath2 = {exprPath, "-", curNumStr};
evaluateWithDFS(num, result, BuildString(buildNewExprPath2), i+1, prevEvalResult - curNum, -curNum, target);
// Try '*' operator
String[] buildNewExprPath3 = {exprPath, "*", curNumStr};
evaluateWithDFS(num, result, BuildString(buildNewExprPath3), i+1, prevEvalResult - prevNumber + prevNumber * curNum, prevNumber * curNum, target);
}
}
}
}
private String BuildString(String[] str) {
StringBuilder sb = new StringBuilder();
for (String s : str) {
sb.append(s);
}
return sb.toString();
}
}