-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0241.为运算表达式设计优先级.java
100 lines (92 loc) · 2.54 KB
/
0241.为运算表达式设计优先级.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @lc app=leetcode.cn id=241 lang=java
*
* [241] 为运算表达式设计优先级
*
* https://leetcode.cn/problems/different-ways-to-add-parentheses/description/
*
* algorithms
* Medium (75.71%)
* Likes: 759
* Dislikes: 0
* Total Accepted: 69.4K
* Total Submissions: 91.7K
* Testcase Example: '"2-1-1"'
*
* 给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
*
* 生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 10^4 。
*
*
*
* 示例 1:
*
*
* 输入:expression = "2-1-1"
* 输出:[0,2]
* 解释:
* ((2-1)-1) = 0
* (2-(1-1)) = 2
*
*
* 示例 2:
*
*
* 输入:expression = "2*3-4*5"
* 输出:[-34,-14,-10,-10,10]
* 解释:
* (2*(3-(4*5))) = -34
* ((2*3)-(4*5)) = -14
* ((2*(3-4))*5) = -10
* (2*((3-4)*5)) = -10
* (((2*3)-4)*5) = 10
*
*
*
*
* 提示:
*
*
* 1 <= expression.length <= 20
* expression 由数字和算符 '+'、'-' 和 '*' 组成。
* 输入表达式中的所有整数值在范围 [0, 99]
*
*
*/
// @lc code=start
class Solution {
private Map<String, List<Integer>> memo = new HashMap<>();
public List<Integer> diffWaysToCompute(String expression) {
List<Integer> result = new ArrayList<>();
if ("".equals(expression))
return result;
if (memo.containsKey(expression))
return memo.get(expression);
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if ('+' == c || '-' == c || '*' == c) {
List<Integer> left = diffWaysToCompute(expression.substring(0, i));
List<Integer> right = diffWaysToCompute(expression.substring(i + 1, expression.length()));
for (Integer x : left) {
for (Integer y : right) {
if ('+' == c)
result.add(x + y);
if ('-' == c)
result.add(x - y);
if ('*' == c)
result.add(x * y);
}
}
}
}
if (result.isEmpty())
result.add(Integer.parseInt(expression));
memo.put(expression, result);
return result;
}
}
// @lc code=end