PracticeNeetCode ↗LeetCode ↗
Given an integer array nums that may contain duplicates, return all possible subsets, with no duplicate subsets in the result.
i > start and nums[i] == nums[i - 1], applied only within the current loop, not across recursion depths.nums.backtrack(start): append a copy of path to the result immediately — every partial path is a valid subset.i from start to len(nums): if i > start and nums[i] == nums[i - 1], skip it to avoid a duplicate subset.nums[i], recurse with backtrack(i + 1), then pop.backtrack(0) and return the result.Time: O(n · 2ⁿ) — Space: O(n) recursion depth
def subsetsWithDup(nums: list[int]) -> list[list[int]]:
nums.sort()
result = []
path = []
def backtrack(start: int) -> None:
result.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return resultHow the solution above works, piece by piece.
path.if i > start and nums[i] == nums[i - 1]: continue: at the same depth, skip a value equal to the previous one; it would start an identical branch.i > start (not i > 0) matters: the first copy at each level is allowed, so [2, 2] can still be formed by going deeper.The recursion tree for nums = [1, 2, 2]:
i > start), so each distinct choice is explored only once. Going deeper can still pick the second 2, giving [1, 2, 2] and [2, 2].