Skip to content

Commit 1eb63ee

Browse files
committed
subsets
1 parent 60bbfc0 commit 1eb63ee

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/subsets/
8+
public class Subsets {
9+
10+
public static void main(String[] args) {
11+
int[] nums = new int[]{1,2,3};
12+
Subsets obj = new Subsets();
13+
List<List<Integer>> resultList = obj.subsets(nums);
14+
System.out.println(Arrays.toString(resultList.toArray()));
15+
}
16+
17+
public List<List<Integer>> subsets(int[] nums) {
18+
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
19+
// dfs
20+
dfs(nums, resultList, new ArrayList<Integer>(), 0);
21+
22+
return resultList;
23+
}
24+
25+
private void dfs(int[] nums, List<List<Integer>> resultList, List<Integer> list, int index) {
26+
// exit
27+
if (nums == null || index == nums.length) {
28+
resultList.add(new ArrayList<Integer>(list));
29+
return;
30+
}
31+
32+
// add item
33+
list.add(nums[index]);
34+
dfs(nums, resultList, list, index + 1);
35+
36+
// not add item
37+
list.remove(list.size() - 1);
38+
dfs(nums, resultList, list, index + 1);
39+
}
40+
}

0 commit comments

Comments
 (0)