-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC241.java
More file actions
65 lines (55 loc) · 1.78 KB
/
LC241.java
File metadata and controls
65 lines (55 loc) · 1.78 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
58
59
60
61
62
63
64
65
/*
* LC241
*/
import java.util.*;
public class LC241 {
public static List<Integer> recur(String exp, int start, int end) {
List<Integer> res = new ArrayList<>();
// Base case
if (start == end) {
int num = exp.charAt(start) - '0';
res.add(num);
return res;
}
if (end - start == 1 && Character.isDigit(exp.charAt(start))) {
// int num1 = exp.charAt(start) - '0';
// int num2 = exp.charAt(end) - '0';
int num = Integer.parseInt(exp.substring(start, end + 1));
res.add(num);
return res;
}
for (int i = start; i <= end; i++) {
if (Character.isDigit(exp.charAt(i))) {
continue;
}
char op = exp.charAt(i);
List<Integer> left = recur(exp, start, i - 1);
List<Integer> right = recur(exp, i + 1, end);
for (int l : left) {
for (int r : right) {
if (op == '*') {
res.add(l * r);
} else if (op == '+') {
res.add(l + r);
} else {
res.add(l - r);
}
}
}
}
return res;
}
public static List<Integer> diffWaysToCompute(String expression) {
int n = expression.length();
return recur(expression, 0, n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the String Here : ");
String str = sc.nextLine();
System.out.println();
List<Integer> ans = diffWaysToCompute(str);
System.out.println(ans.toString());
sc.close();
}
}