forked from algorithm001/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_241_129.java
More file actions
57 lines (54 loc) · 1.77 KB
/
Copy pathLeetCode_241_129.java
File metadata and controls
57 lines (54 loc) · 1.77 KB
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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LeetCode_241_129 {
private Map<String, List<Integer>> memo = new HashMap<>();
public List<Integer> diffWaysToCompute(String input) {
int len = input.length();
// check history
List<Integer> result = memo.get(input);
if (result != null) {
return result;
}
result = new ArrayList<>();
// base case
if (isDigit(input)) {
result.add(Integer.parseInt(input));
memo.put(input, result);
return result;
}
for (int i = 0; i < len; 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, len));
for (Integer il : left) {
for (Integer ir : right) {
switch (c) {
case '+':
result.add(il + ir);
break;
case '-':
result.add(il - ir);
break;
case '*':
result.add(il * ir);
break;
}
}
}
}
}
memo.put(input, result);
return result;
}
private boolean isDigit(String s) {
for (Character c : s.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
}