-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDifferent Ways to Add Parentheses.java
38 lines (34 loc) · 1.29 KB
/
Different Ways to Add Parentheses.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
// Runtime: 2 ms (Top 79.5%) | Memory: 41.16 MB (Top 75.1%)
class Solution {
Map<String, List<Integer>> memo = new HashMap<>();
public List<Integer> diffWaysToCompute(String expression) {
List<Integer> res = new LinkedList<>();
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 == '-'){
//divide
List<Integer> left = diffWaysToCompute(expression.substring(0, i));
List<Integer> right = diffWaysToCompute(expression.substring(i+1));
//conquer
for(int a : left){
for(int b : right){
if(c == '+'){
res.add(a+b);
}else if(c == '-'){
res.add(a - b);
}else if(c == '*'){
res.add(a * b);
}
}
}
}
}
//base case, when there is no operator
if(res.isEmpty()){
res.add(Integer.parseInt(expression));
}
memo.put(expression, res);
return res;
}
}