[LeetCode] 282. Expression Add Operators
Posted CNoodle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 282. Expression Add Operators相关的知识,希望对你有一定的参考价值。
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.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
Example 4:Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:Input: num = "3456237490", target = 9191
Output: []
给表达式添加运算符。题意是给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加二元运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。
思路是DFS backtracking,一点点去尝试。helper函数里包括了这么几个参数
res - 最终的结果
path - 当前被构建的运算表达式
curNum - 当前被构建的数字
preNum - 之前一个被构建的数字
加减法比较好理解,这里乘法的部分稍微有点绕,我参考了这个帖子,帮助理解。乘法的结果 = curNum - preNum + preNum * curNum,乘法操作完毕之后,之前一个被构建的数字也就变成了preNum * curNum。
时间 - not sure
空间 - O(n)
Java实现
1 class Solution { 2 public List<String> addOperators(String num, int target) { 3 List<String> res = new ArrayList<>(); 4 // corner case 5 if (num == null || num.length() == 0) { 6 return res; 7 } 8 helper(res, "", num, target, 0, 0, 0); 9 return res; 10 } 11 12 private void helper(List<String> res, String path, String num, int target, int pos, long curRes, long preNum) { 13 // corner case 14 if (pos == num.length()) { 15 if (target == curRes) { 16 res.add(path); 17 return; 18 } 19 } 20 for (int i = pos; i < num.length(); i++) { 21 if (i != pos && num.charAt(pos) == \'0\') { 22 return; 23 } 24 long curNum = Long.valueOf(num.substring(pos, i + 1)); 25 if (pos == 0) { 26 helper(res, path + curNum, num, target, i + 1, curNum, curNum); 27 } else { 28 helper(res, path + "+" + curNum, num, target, i + 1, curRes + curNum, curNum); 29 helper(res, path + "-" + curNum, num, target, i + 1, curRes - curNum, -curNum); 30 helper(res, path + "*" + curNum, num, target, i + 1, curRes - preNum + preNum * curNum, 31 preNum * curNum); 32 } 33 } 34 } 35 }
以上是关于[LeetCode] 282. Expression Add Operators的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode282. Expression Add Operators
LeetCode282. Expression Add Operators
leetcode282 - Expression Add Operators - hard