Skip to content

Commit f91a968

Browse files
committed
subsets II
1 parent 8c1c93a commit f91a968

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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-ii/
8+
public class SubsetsII {
9+
10+
public static void main(String[] args) {
11+
int[] nums = {1,2,2};
12+
SubsetsII obj = new SubsetsII();
13+
List<List<Integer>> resultList = obj.subsetsWithDup(nums);
14+
System.out.println(Arrays.toString(resultList.toArray()));
15+
}
16+
17+
public List<List<Integer>> subsetsWithDup(int[] nums) {
18+
Arrays.sort(nums);
19+
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
20+
// dfs
21+
dfs(nums, resultList, new ArrayList<Integer>(), 0);
22+
23+
return resultList;
24+
}
25+
26+
private void dfs(int[] nums, List<List<Integer>> resultList, List<Integer> list, int start) {
27+
if (start <= nums.length) {
28+
resultList.add(list);
29+
}
30+
int i = start;
31+
while (i < nums.length) {
32+
list.add(nums[i]);
33+
dfs(nums, resultList, new ArrayList<Integer>(list), i + 1);
34+
35+
list.remove(list.size() - 1);
36+
i++;
37+
while (i < nums.length && nums[i] == nums[i - 1]) {
38+
i++;
39+
}
40+
}
41+
42+
}
43+
44+
// still have some duplicate data
45+
//private void dfs1(int[] nums, List<List<Integer>> resultList, List<Integer> list, int start) {
46+
// // exit
47+
// if (start == nums.length) {
48+
// resultList.add(new ArrayList<>(list));
49+
// return;
50+
// }
51+
//
52+
// for (int i = start; i < nums.length; i++) {
53+
// // duplicate case
54+
// if (i > start && nums[i] == nums[i - 1]) {
55+
// continue;
56+
// }
57+
//
58+
// // pick up
59+
// list.add(nums[i]);
60+
// dfs(nums, resultList, list, i + 1);
61+
//
62+
// // not pick up
63+
// list.remove(list.size() - 1);
64+
// dfs(nums, resultList, list, i + 1);
65+
// }
66+
//}
67+
}

0 commit comments

Comments
 (0)