-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDifferentWaystoAddParentheses.java
More file actions
33 lines (33 loc) · 1.32 KB
/
DifferentWaystoAddParentheses.java
File metadata and controls
33 lines (33 loc) · 1.32 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
public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> results = new ArrayList<>();
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
if (c == '*' || c == '+' || c == '-') {
String left = input.substring(0, i);
String right = input.substring(i + 1, input.length());
List<Integer> leftResults = diffWaysToCompute(left);
List<Integer> rightResults = diffWaysToCompute(right);
for (int leftResult : leftResults) {
for (int rightResult : rightResults) {
switch(c) {
case '+':
results.add(leftResult + rightResult);
break;
case '-':
results.add(leftResult - rightResult);
break;
case '*':
results.add(leftResult * rightResult);
break;
}
}
}
}
}
if (results.size() == 0) {
results.add(Integer.parseInt(input));
}
return results;
}
}