Total Accepted: 8828 Total Submissions: 32877
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) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
list.add(new ArrayList<Integer>());
Arrays.sort(num);
dfs(num, list, path, 0);
return list;
}
public void dfs(int[] num, ArrayList<ArrayList<Integer>> list, ArrayList<Integer> path, int index) {
for (int i = index; i < num.length; i++) {
path.add(num[i]);
list.add(new ArrayList<Integer>(path));
dfs(num, list, path, i + 1);
path.remove(path.size() - 1);
while (i < num.length - 1 && num[i] == num[i+1]) i++;
}
}
}
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
list.add(new ArrayList<Integer>());
Arrays.sort(num);
dfs(num, list, path, 0);
return list;
}
public void dfs(int[] num, ArrayList<ArrayList<Integer>> list, ArrayList<Integer> path, int index) {
if (index < num.length) {
path.add(num[index]);
list.add(new ArrayList<Integer>(path));
dfs(num, list, path, index + 1);
path.remove(path.size() - 1);
// get next index num[index] != num[index']
while (index < num.length - 1 && num[index] == num[index+1]) index++;
dfs(num, list, path, index + 1);
}
}
}