Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note:The solution set must not contain duplicate subsets.
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null) {
res.add(new ArrayList<Integer>());
return res;
}
boolean[] visited = new boolean[nums.length];
Arrays.sort(nums);
for(int i = 0; i <= nums.length; i++)
helper(res, new ArrayList<Integer>(), nums, visited, 0, i);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> line, int[] nums, boolean[] visited, int start, int size) {
if(line.size() == size) {
res.add(new ArrayList<>(line));
return;
}
for(int i = start; i < nums.length; i++) {
if(i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])
continue;
line.add(nums[i]);
visited[i] = true;
helper(res, line, nums, visited, i + 1, size);
visited[i] = false;
line.remove(line.size() - 1);
}
}
}