-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSubsets.java
More file actions
50 lines (46 loc) · 1.12 KB
/
Subsets.java
File metadata and controls
50 lines (46 loc) · 1.12 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
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author eko
* @date 2018/10/24 10:42 AM
*
* 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],
* []
* ]
*/
public class Subsets {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = new Subsets().subsets(nums);
System.out.println(res);
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, res, new ArrayList<>(), 0);
return res;
}
public void backtrack(int[] nums, List<List<Integer>> lists, List<Integer> list, int start) {
lists.add(new ArrayList<>(list));
for (int i = start; i < nums.length; i++) {
list.add(nums[i]);
backtrack(nums, lists, list, i + 1);
list.remove(list.size() - 1);
}
}
}