-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets.java
More file actions
48 lines (39 loc) · 1016 Bytes
/
Copy pathSubsets.java
File metadata and controls
48 lines (39 loc) · 1016 Bytes
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
/*
78. Subsets (https://leetcode.com/problems/subsets/)
Medium
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
*/
package recusion;
import java.util.ArrayList;
import java.util.List;
public class Subsets {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
createItem(list, new ArrayList<Integer>(), nums, 0);
return list;
}
private static void createItem(List<List<Integer>> list, List<Integer> items, int[] nums, int start) {
if (items != null) {
list.add(new ArrayList<Integer>(items));
}
for (int i = start; i < nums.length; i++) {
items.add(nums[i]);
createItem(list, items, nums, i + 1);
items.remove(items.size() - 1);
}
}
}