-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSubsets.java
More file actions
56 lines (49 loc) · 1.62 KB
/
Subsets.java
File metadata and controls
56 lines (49 loc) · 1.62 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
package permutationcombination;
// Source : https://leetcode.com/problems/subsets/
// Id : 78
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2021/2/20
// Topic : combination
// Level : Medium
// Other :
// Tips :
// Links : Must
// Result : 82.14% 5.24%
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Subsets {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(nums);
combination(nums, 0, res, new LinkedList<>());
return res;
}
private void combination(int[] nums, int start, List<List<Integer>> ans, List<Integer> path) {
ans.add(new LinkedList<Integer>(path));
if (start > nums.length)
return;
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
combination(nums, i + 1, ans, path);
path.remove(path.size() - 1);
}
}
public List<List<Integer>> subsets1(int[] nums) {
// public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
backtracking(0, nums, new ArrayList<>(), ans);
return ans;
}
private void backtracking(int start, int[] nums, List<Integer> path, List<List<Integer>> ans) {
if (start == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
path.add(nums[start]);
backtracking(start + 1, nums, path, ans);
path.remove(path.size() - 1);
backtracking(start + 1, nums, path, ans);
}
}