LeetCode

Subsets II

Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:

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

Java

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> sols = new ArrayList<List<Integer>>();
        if(nums == null) {
            return null;
        }
        Arrays.sort(nums);
        sols.add(new ArrayList<Integer>());
        helper(nums, 0, new ArrayList<Integer>(), sols);
        return sols;
    }

    private void helper(int[] nums, int start, List<Integer> sol, List<List<Integer>> sols) {
        for(int i = start; i < nums.length; i++) {
            sol.add(nums[i]);
            sols.add(new ArrayList<Integer>(sol));
            helper(nums, i + 1, sol, sols);
            sol.remove(sol.size() - 1);
            while(i < nums.length - 1 && nums[i] == nums[i + 1]) {
                i++;
            }
        }
    }
}