Skip to main content

Subsets II

Question

How can I generate all unique subsets of a given set of distinct integers, while taking into account the presence of duplicates in the set?

Example 1
Input: [1,2,2]

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

Solution

all//Subsets II.py


def subsets_ii(nums):
res = [[]]
nums.sort()
for num in nums:
res += [item+[num] for item in res if item+[num] not in res]
return res