forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubsets.java
62 lines (49 loc) · 1.63 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
53
54
55
56
57
58
59
60
61
62
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* 思路是对每个index,有两种情况,要还是不要
* 要注意的是添加结果到result时,要复制一个列表,别直接加list
*/
public class Subsets {
/**
* 时间复杂度O(2^n),空间复杂度 O(n)
*/
/**
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (nums.length == 0) {
return result;
}
subsets(nums, 0, result, new LinkedList<Integer>());
return result;
}
private void subsets(int[] nums, int start, List<List<Integer>> list, List<Integer> path) {
if (start == nums.length) {
list.add(new LinkedList<Integer>(path));
return;
}
path.add(nums[start]);
subsets(nums, start + 1, list, path);
path.remove(path.size() - 1);
subsets(nums, start + 1, list, path);
}
*/
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (nums.length == 0) {
return result;
}
Arrays.sort(nums);
subsets(nums, 0, result, new LinkedList<Integer>());
return result;
}
private void subsets(int[] nums, int start, List<List<Integer>> result, List<Integer> path) {
result.add(new LinkedList<Integer>(path));
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
subsets(nums, i + 1, result, path);
path.remove(path.size() - 1);
}
}
}