-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerateExpression.java
65 lines (50 loc) · 1.81 KB
/
GenerateExpression.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
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
import java.util.ArrayList;
import java.util.List;
//282 leetcode with minor difference
//TC = O( 3 ^ n-1) * n
//SC = O(n) + O(1)*n + O( 3 ^ n-1) * n
public class GenerateExpression {
static public List<String> result = new ArrayList<>();
static public long target = 24;
private static void helper(String nums, int idx, List<Character> slate, long target, long curSum, Long curProduct, int curNum) {
//backTracking
if(curSum > target)
return;
if(idx == nums.length()) {
if(curSum+curProduct*curNum == target) {
StringBuilder sb = new StringBuilder();
for(char i : slate) {
sb.append(i);
}
result.add(sb.toString());
}
return;
}
//concatinate
slate.add(nums.charAt(idx));
helper(nums,idx+1, slate, target, curSum, curProduct, curNum*10+(nums.charAt(idx) -'0'));
slate.remove(slate.size()-1);
//"+"
slate.add('+');
slate.add(nums.charAt(idx));
helper(nums,idx+1, slate, target, curSum+curProduct*curNum, 1L, nums.charAt(idx)-'0');
slate.remove(slate.size()-1);
slate.remove(slate.size()-1);
//*
slate.add('*');
slate.add(nums.charAt(idx));
helper(nums,idx+1, slate, target, curSum, curProduct*curNum, nums.charAt(idx)-'0');
slate.remove(slate.size()-1);
slate.remove(slate.size()-1);
}
public static void main(String[] args) {
String nums = "1234";
List<Character> slate = new ArrayList<>();
slate.add(nums.charAt(0));
Long curSum = 0L;
long curProduct = 1L;
int idx = 0;
helper(nums, 1, slate, 11, 0L, 1L, nums.charAt(0)-'0');
System.out.println(result);
}
}