forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Subsets.java
52 lines (44 loc) · 1.02 KB
/
Subsets.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
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Given a set of distinct integers, nums, return all possible subsets (the power set).
* <p>
* Note: The solution set must not contain duplicate subsets.
* <p>
* For example,
* If nums = [1,2,3], a solution is:
* <p>
* [
* [3],
* [1],
* [2],
* [1,2,3],
* [1,3],
* [2,3],
* [1,2],
* []
* ]
* <p>
* Accepted.
*/
public class Subsets {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new LinkedList<>();
results.add(new LinkedList<>());
if (nums == null || nums.length == 0) {
return results;
}
Arrays.sort(nums);
for (int i : nums) {
int size = results.size();
for (int j = 0; j < size; j++) {
List<Integer> list = new LinkedList<>();
list.addAll(results.get(j));
list.add(i);
results.add(list);
}
}
return results;
}
}