90. Subsets II

Description

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.

Constraints

Approach

Examples

Input: [1, 2, 2]

Output: [ [], [1], [1, 2], [2], [1, 2, 2], [2, 2] ]

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> subsets = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(subsets, new LinkedList<Integer>(), nums, 0);
        return subsets;
    }

    private void backtrack(List<List<Integer>> subsets,
                          LinkedList<Integer> subset,
                          int[] nums,
                          int index) {
        subsets.add(new ArrayList(subset));
        for(int i = index; i < nums.length; i++) {
            if (i > index && nums[i-1] == nums[i]) continue;
            subset.add(nums[i]);
            backtrack(subsets, subset, nums, i+1);
            subset.removeLast();
        }
    }
}

Follow up

Last updated

Was this helpful?