Problem 282: Expression Add Operators
思路
public class Solution {
public List<String> addOperators(String num, int target) {
List<String> rst = new ArrayList<>();
if (num == null || num.length() == 0) return rst;
helper(num, target, 0, 0, 0, "", rst);
return rst;
}
private void helper(String num, int target, int pos, long calc, long prev, String path, List<String> rst) {
if (pos == num.length() && calc == target) {
rst.add(path);
return;
}
for (int i = pos; i < num.length(); i++) {
if (num.charAt(pos) == '0' && i != pos) break;
long cur = Long.parseLong(num.substring(pos, i + 1));
if (pos == 0) {
helper(num, target, i + 1, cur, cur, path + cur, rst);
} else {
helper(num, target, i + 1, calc + cur, cur, path + "+" + cur, rst);
helper(num, target, i + 1, calc - cur, -cur, path + "-" + cur, rst);
helper(num, target, i + 1, calc - prev + cur * prev, cur * prev, path + "*" + cur, rst);
}
}
}
}易错点
Last updated