-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets.java
More file actions
69 lines (55 loc) · 1.83 KB
/
Subsets.java
File metadata and controls
69 lines (55 loc) · 1.83 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
package solutions;
import java.util.ArrayList;
import java.util.List;
// [Problem] https://leetcode.com/problems/subsets/
class Subsets {
// test
public static void main(String[] args) {
Subsets solution = new Subsets();
int[] input = {1, 2, 3};
List<List<Integer>> output = solution.subsets(input);
System.out.println(output);
// expected output =
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
}
// Cascading solution - O(n * 2^n) time, O(n * 2^n) space
public List<List<Integer>> subsetsCascading(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
subsets.add(new ArrayList<>());
for (int num : nums) {
List<List<Integer>> newSubsets = new ArrayList<>();
for (List<Integer> subset : subsets) {
newSubsets.add(new ArrayList<>(subset) {{
add(num);
}});
}
subsets.addAll(newSubsets);
}
return subsets;
}
// Bit manipulation solution - O(n * 2^n) time, O(n * 2^n) space
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
int n = nums.length;
for (int i = (int) Math.pow(2, n); i < (int) Math.pow(2, n + 1); i++) {
// generate bitmask, from 0..00 to 1..11
String bitmask = Integer.toBinaryString(i).substring(1);
// append subset corresponding to that bitmask
List<Integer> subset = new ArrayList<>();
for (int j = 0; j < n; ++j) {
if (bitmask.charAt(j) == '1') subset.add(nums[j]);
}
subsets.add(subset);
}
return subsets;
}
}