-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets0078.java
More file actions
39 lines (30 loc) · 942 Bytes
/
Subsets0078.java
File metadata and controls
39 lines (30 loc) · 942 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
import java.util.ArrayList;
import java.util.List;
/**
* leetcode回溯法:子集
* 该题比较难,回溯算法的精髓在于平行宇宙的概念(自创的)
*/
public class Subsets0078{
public static void main(String[] args) {
int nums[] = {1,2,3};
subsets(nums);
}
private static List<List<Integer>> result = new ArrayList<List<Integer>>();
public static List<List<Integer>> subsets(int[] nums) {
List<Integer> tmp = new ArrayList<>();
backtrack(nums, 0, tmp);
return result;
}
private static void backtrack(int[] nums, int start, List<Integer> tmp) {
result.add(new ArrayList<>(tmp));
for (int i = start; i < nums.length; i++) {
tmp.add(nums[i]);
backtrack(nums, i+1, tmp);
tmp.remove(tmp.size()-1);
}
for (int j : tmp) {
System.out.print(j + " ");
}
System.out.println();
}
}