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"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> []
public class Solution {
public List<String> addOperators(String num, int target) {
List<String> res = new ArrayList<String>();
if (num == null || num.length() == 0) {
return res;
}
helper(num, target, "", 0, 0, 0, res);
return res;
}
private void helper(String num, int target, String expression, int pos, long total, long lastVal, List<String> res) {
if (pos == num.length()) {
if (total == target) {
res.add(expression);
}
}
for (int i = pos; i < num.length(); i++) {
if (i != pos && num.charAt(pos) == '0') {
break;
}
long val = Long.parseLong(num.substring(pos, i + 1));
if (pos == 0) {
helper(num, target, expression + num.substring(pos, i + 1), i + 1, total + val, val, res);
} else {
helper(num, target, expression + "+" + val, i + 1, total + val, val, res);
helper(num, target, expression + "-" + val, i + 1, total - val, -val, res);
helper(num, target, expression + "*" + val, i + 1, total - lastVal + val * lastVal, val * lastVal, res);
}
}
}
}
没有评论:
发表评论