-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
51 lines (46 loc) · 1.31 KB
/
Copy pathSolution.java
File metadata and controls
51 lines (46 loc) · 1.31 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
import java.util.ArrayList;
import java.util.List;
public class Solution
{
public List<Integer> diffWaysToCompute(String input)
{
return getWays(input, 0, input.length() - 1);
}
private List<Integer> getWays(String input, int start, int end)
{
List<Integer> result = new ArrayList<>();
for (int i = start; i <= end; i++)
{
if (input.charAt(i) == '*' || input.charAt(i) == '+' || input.charAt(i) == '-')
{
char operator = input.charAt(i);
List<Integer> left = getWays(input, start, i - 1);
List<Integer> right = getWays(input, i + 1, end);
for (Integer l : left)
{
for (Integer r : right)
{
result.add(operationResult(l, r, operator));
}
}
}
}
if (result.isEmpty())
{
result.add(Integer.parseInt(input.substring(start, end + 1)));
}
return result;
}
private Integer operationResult(Integer l, Integer r, char operator)
{
if (operator == '+')
{
return l + r;
}
else if (operator == '-')
{
return l - r;
}
return l * r;
}
}