forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsetsII.java
50 lines (30 loc) · 1.17 KB
/
subsetsII.java
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
// Given a collection of integers that might contain duplicates, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,2], a solution is:
// [
// [2],
// [1],
// [1,2,2],
// [2,2],
// [1,2],
// []
// ]
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums.length == 0 || nums == null) return result;
helper(nums, new ArrayList<Integer>(), 0, result);
return result;
}
public void helper(int[] nums, ArrayList<Integer> current, int index, List<List<Integer>> result) {
result.add(current);
for(int i = index; i < nums.length; i++) {
if(i > index && nums[i] == nums[i - 1]) continue;
ArrayList<Integer> newCurrent = new ArrayList<Integer>(current);
newCurrent.add(nums[i]);
helper(nums, newCurrent, i + 1, result);
}
}
}