码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 282. Expression Add Operators

时间:2020-05-21 09:38:29      阅读:44      评论:0      收藏:0      [点我收藏+]

标签:value   add   char   之间   solution   ase   ++   su-   and   

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 题目总结

[LeetCode] 282. Expression Add Operators

标签:value   add   char   之间   solution   ase   ++   su-   and   

原文地址:https://www.cnblogs.com/cnoodle/p/12928364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!