SDE & MLE Prep

90. Subsets II

Problem

nums may contain duplicates. Return every distinct subset, in any order, without listing the same subset twice.

Example: [1,2,2] → [[],[1],[1,2],[1,2,2],[2],[2,2]]

Constraints: n ≤ 10.

Sort; at the same depth skip a value equal to its left neighbour (i > start), so each distinct choice branches once.

Complexity: O(n · 2ⁿ).

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res, path = [], []

        def bt(start):
            res.append(path[:])
            for i in range(start, len(nums)):
                if i > start and nums[i] == nums[i - 1]:
                    continue
                path.append(nums[i])
                bt(i + 1)
                path.pop()

        bt(0)
        return res