Given a list of numbers that may has duplicate numbers, return all possible subsets
class Solution {
/** * @param nums: A set of numbers. * @return: A list of lists. All valid subsets. */
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
if (nums == null || nums.length == 0) {
return results;
}
ArrayList<Integer> subset = new ArrayList<>();
Arrays.sort(nums);
dfsHelp(nums, 0, subset, results);
return results;
}
private void dfsHelp(int[] nums,
int index,
ArrayList<Integer> subset,
ArrayList<ArrayList<Integer>> results) {
results.add(new ArrayList<Integer>(subset));
for (int i = index; i < nums.length; i++) {
if (i != index && nums[i] == nums[i - 1]) {
continue;
}
subset.add(nums[i]);
dfsHelp(nums, i + 1, subset, results);
subset.remove(subset.size() - 1);
}
}
}