Subsets II

Medium

Topics
ArrayBacktrackingBit Manipulation

Given an integer array nums that may contain duplicates, return all possible unique subsets. The result may be in any order.

Example 1

[][1][2][1,2][2,2][1,2,2]
Duplicates in the input would otherwise produce the same subset twice. Sorting first puts equal values together, and then the rule is to skip a value whose equal predecessor was not taken at this level — which keeps each distinct subset exactly once. 6 here, not 8.
Each chip is one distinct subset.
Input:  nums = [1,2,2]
Output: [[],[1],[2],[1,2],[2,2],[1,2,2]]

Example 2

[][0]
Input:  nums = [0]
Output: [[],[0]]

Constraints

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
Editorial — intuition, approach, complexity and pitfalls

Intuition

Duplicates cause repeated subsets. Sort first so equal values are adjacent, then at each recursion level skip a value identical to the previous choice at that same level.

Approach

  1. Sort nums.
  2. DFS recording each partial subset; iterate candidates from start.
  3. Skip nums[i] == nums[i-1] when i > start to avoid duplicate subsets.

Dry Run

nums = [1, 2, 2] (already sorted; sorting is what puts equal values adjacent)
  emit []            loop i from 0
    emit [1]           loop i from 1
      emit [1, 2]        loop i from 2
        emit [1, 2, 2]
      i=2: nums[2] == nums[1] and i > start  ->  skip
    emit [2]           loop i from 2
      emit [2, 2]
  i=2: nums[2] == nums[1] and i > start  ->  skip
answer [] | [1] | [1,2] | [1,2,2] | [2] | [2,2]
The condition is `i > start`, and the two skips in the trace show why. At the
outer level start is 0, so i=2 is skipped -- choosing the second 2 as the FIRST
element would re-generate everything the first 2 already produced. But inside the
[2] branch start is 2, so i=2 is NOT skipped, and [2,2] is generated: using a
duplicate value again at a deeper position is a genuinely different subset.
Change it to `i > 0` and the skip stops being position-aware. Every repeated
value is refused everywhere, and the output collapses to
[] [1] [1,2] [2] -- both [1,2,2] and [2,2] disappear.
So the rule is "do not start a new branch with a value already tried at this
level", not "never repeat a value".

Complexity

  • Time — O(n * 2^n): up to 2^n subsets copied in O(n).
  • Space — O(n): recursion depth.

Common Pitfalls

  • Skip only when i > start; skipping at i == start would drop valid subsets.

Full Solution — all languages

class Solution:
    def subsetsWithDup(self, nums):
        nums.sort()
        res=[]
        def dfs(start,path):
            res.append(path[:])
            for i in range(start,len(nums)):
                if i>start and nums[i]==nums[i-1]: continue
                path.append(nums[i]); dfs(i+1,path); path.pop()
        dfs(0,[])
        return res
SensAI
Beta
Tap the mic to stop voice mode