-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode0241.java
51 lines (46 loc) · 1.59 KB
/
LeetCode0241.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
/* Different Ways to Add Parentheses
* Input: "2*3-4*5"
* Output: [-34, -14, -10, -10, 10]
* Explanation:
* (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
* */
import java.util.ArrayList;
import java.util.List;
public class LeetCode0241 {
public static void main(String[] args) {
String input = "2-1-1";
System.out.println(diffWaysToCompute(input));
}
public static List<Integer> diffWaysToCompute(String input) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
List<Integer> left = diffWaysToCompute(input.substring(0, i)); // substring截取至第i-1个
List<Integer> right = diffWaysToCompute(input.substring(i + 1));
for (int l : left) {
for (int r : right) {
switch (c) {
case '+':
res.add(l + r);
break;
case '-':
res.add(l - r);
break;
case '*':
res.add(l * r);
break;
}
}
}
}
}
if (res.isEmpty())
res.add(Integer.valueOf(input));
return res;
}
}