forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets II.java
More file actions
38 lines (34 loc) · 1.06 KB
/
Subsets II.java
File metadata and controls
38 lines (34 loc) · 1.06 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
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
Arrays.sort(num);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
subsets(num, 0, path, result);
return result;
}
private void subsets(int[] num, int begin, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> result) {
result.add(new ArrayList<Integer>(path));
for (int i = begin; i < num.length; i++) {
if (i > begin && num[i - 1] == num[i]) {
continue;
}
path.add(num[i]);
subsets(num, i + 1, path, result);
path.remove(path.size() - 1);
}
}
}