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 -> []
这道题要找到 所有的解法, 所有要用到 DFS来得到所有的解。
这里用到一个 trick。 1 + 2 * 3 如果按照顺序的话,事先计算 1 + 2 (等于 3), 然后轮到了 乘法 (*)。我们这里要 从 3 里 减去 2 然后 加上 2 * 3, 1 + 2 - 2 + 2 * 3。 所以要用multi 来 记录 上一步 的数。
public List<String> addOperators(String num, int target) {
List<String> res = new ArrayList<>();
if (num == null || num.length() == 0) return res;
helper(res, num, target, "", 0, 0, 0);
return res;
}
private void helper(List<String> res, String num, int target, String tmp, int pos, long eval, long multi) {
if (pos == num.length()) {
if (target == eval) {
res.add(tmp);
}
return;
}
for (int i = pos; i < num.length(); i++) {
if (i != pos && num.charAt(pos) == '0') break;
long cur = Long.parseLong(num.substring(pos, i + 1));
if (pos == 0) helper(res, num, target, tmp + cur, i + 1, cur, cur);
else {
helper(res, num, target, tmp + "+" + cur, i + 1, eval + cur, cur );
helper(res, num, target, tmp + "-" + cur, i + 1, eval - cur, -cur);
helper(res, num, target, tmp + "*" + cur, i + 1, eval - multi + multi * cur, multi * cur);
}
}
}
本文介绍了一种算法,该算法可以接收一个仅包含0-9数字的字符串和一个目标值,返回所有可能的方式,在数字之间添加+、-或*运算符使表达式计算结果等于目标值。文章详细解释了深度优先搜索(DFS)策略的应用,并提供了一个具体的Java实现示例。
4万+

被折叠的 条评论
为什么被折叠?



