-
Notifications
You must be signed in to change notification settings - Fork 18
/
DiffWaysToCompute_241.java
49 lines (44 loc) · 1.43 KB
/
DiffWaysToCompute_241.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
package 分治;
import java.util.ArrayList;
import java.util.List;
/**
* @Author jiangyunxiong
* @Date 2018/12/20 下午11:24
*
* 给表达式加括号
*/
public class DiffWaysToCompute_241 {
public static void main(String[] args) {
DiffWaysToCompute_241 n = new DiffWaysToCompute_241();
n.diffWaysToCompute("2-1-1");
}
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ways = 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));
List<Integer> right = diffWaysToCompute(input.substring(i + 1));
for (int l : left) {
for (int r : right) {
switch (c) {
case '+':
ways.add(l + r);
break;
case '-':
ways.add(l - r);
break;
case '*':
ways.add(l * r);
break;
}
}
}
}
}
if (ways.size() == 0) {
ways.add(Integer.valueOf(input));
}
return ways;
}
}