-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday35.java
More file actions
82 lines (66 loc) · 2.35 KB
/
Copy pathday35.java
File metadata and controls
82 lines (66 loc) · 2.35 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//ques1:78. Subsets
//link:https://leetcode.com/problems/subsets/
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> lol = new ArrayList<>();
lol.add(new ArrayList<>()); // Add the empty subset
int l = nums.length;
for (int k = 1; k <= l; k++) { // Iterate over subset sizes
List<Integer> list = new ArrayList<>();
generateSubsets(nums, 0, k, list, lol); // Generate subsets of size k
}
return lol;
}
private void generateSubsets(int[] nums, int start, int k, List<Integer> list, List<List<Integer>> lol) {
if (list.size() == k) {
lol.add(new ArrayList<>(list)); // Add the current subset
return;
}
for (int i = start; i < nums.length; i++) {
list.add(nums[i]); // Choose
generateSubsets(nums, i + 1, k, list, lol); // Explore further
list.remove(list.size() - 1); // Backtrack (un-choose)
}
}
}
//ques2:22. Generate Parentheses
//link:https://leetcode.com/problems/generate-parentheses/description/
class Solution2 {
public List<String> generateParenthesis(int n) {
List<List<String>> lol = new ArrayList<>();
List<String> list = new ArrayList<>();
list.add("(");
generate(1, 0, lol, list, n);
List<String> flatList = new ArrayList<>();
for (List<String> subList : lol) {
flatList.add(String.join("", subList));
}
return flatList;
}
public void generate(int countop, int countcl, List<List<String>> lol, List<String> list, int n) {
int c = 0;
if (list.size() == 2 * n) {
lol.add(new ArrayList<>(list));
return;
}
if (countop == n) {
for (int i = countcl; i < n; i++) {
list.add(")");
c++;
}
lol.add(new ArrayList<>(list));
for (int i = 0; i < c; i++) {
list.remove(list.size() - 1);
}
return;
}
list.add("(");
generate(countop + 1, countcl, lol, list, n);
list.remove(list.size() - 1);
if (countop > countcl) {
list.add(")");
generate(countop, countcl + 1, lol, list, n);
list.remove(list.size() - 1);
}
}
}