# Subsets II

Medium

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.

Example:

``````Input:
[1,2,2]

Output:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]``````

## Solution

Backtracking

``````class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
helper(nums, 0, new ArrayList<Integer>(), res);
return res;
}
private void helper(int[] nums, int start, List<Integer> subset, List<List<Integer>> res) {
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
helper(nums, i + 1, subset, res);
subset.remove(subset.size() - 1);
}
}
}``````

Iterative

``````public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<List<Integer>>();
int begin = 0;
for(int i = 0; i < nums.length; i++){
if(i == 0 || nums[i] != nums[i - 1]) begin = 0;
int size = result.size();
for(int j = begin; j < size; j++){
List<Integer> cur = new ArrayList<Integer>(result.get(j));