subsets II

🏠

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.

 1 Input: [1,2,2]
 2 Output:
 3 [
 4   [2],
 5   [1],
 6   [1,2,2],
 7   [2,2],
 8   [1,2],
 9   []
10 ]
1 def subsetsWithDup(nums):
2   nums.sort()
3   res = {tuple(nums)}
4   subs = {tuple(nums)}
5   while subs:
6       subs = {sub[:i] + sub[i+1:] for sub in subs for i in range(len(sub))}
7       res |= subs
8   return res
1 def subsetsWithDup(nums):
2   res = [[]]
3   nums.sort()
4   for num in nums: 
5       res += [ i + [num] for i in res if i + [num] not in res]
6   return res