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 -> []
Solution:
The idea is using DFS and cut the string to numbers.
When we cut and get a number, we have three choices:
1. multiply
2. add
3. subtract
Therefore we maintains lastFactor to deal with these cases:
1.
sum = sum - lastFactor + lastFactor * currNum
lastFactor = lastFactor * currNum
2.
sum = sum + currNum
lastFactor = currNum
3.
sum = sum - currNum
lastFactor = -currNum
Corner case:
1. No sign at the beginning of the string.
2. After a cut, the number cannot start with '0'.
Code:
public class Solution { public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<>(); if (num == null || num.length() == 0) { return result; } helper(num, result, target, "", 0, 0, 0); return result; } public void helper(String num, List<String> result, int target, String path, long factor, long sum, int pos) { if (pos == num.length() && sum == target) { result.add(path); return; } for (int i = pos; i < num.length(); i++) { if (i != pos && num.charAt(pos) == '0') { break; } String currStr = num.substring(pos, i + 1); long currNum = Long.parseLong(currStr); if (pos == 0) { helper(num, result, target, currStr, currNum, currNum, i + 1); } else { helper(num, result, target, path + "*" + currStr, factor * currNum, sum - factor + factor * currNum, i + 1); helper(num, result, target, path + "+" + currStr, currNum, sum + currNum, i + 1); helper(num, result, target, path + "-" + currStr, -currNum, sum - currNum, i + 1); } } } }