forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsets2.java
72 lines (61 loc) · 2.15 KB
/
subsets2.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
// write your code here
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null) return results;
if (nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
List<Integer> subset = new ArrayList<Integer>();
helper(nums, 0, subset, results);
return results;
}
public void helper(int[] nums, int startIndex, List<Integer> subset, List<List<Integer>> results){
results.add(new ArrayList<Integer>(subset));
for(int i=startIndex; i<nums.length; i++){
if (i != startIndex && nums[i]==nums[i-1]) {
continue;
}
subset.add(nums[i]);
helper(nums, i+1, subset, results);
subset.remove(subset.size()-1);
}
}
}
// return ArrayList<ArrayList<Integer>>
class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
// write your code here
List<List<Integer>> results = new ArrayList<>();
if (nums == null) return results;
if (nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
ArrayList<Integer> subset = new ArrayList<>();
helper(nums, 0, subset, results);
return results;
}
public void helper(int[] nums, int startIndex, List<Integer> subset, List<List<Integer>> results){
results.add(new ArrayList<Integer>(subset));
for(int i=startIndex; i<nums.length; i++){
if (i != startIndex && nums[i]==nums[i-1]) {
continue;
}
subset.add(nums[i]);
helper(nums, i+1, subset, results);
subset.remove(subset.size()-1);
}
}
}