subsets-iiV1.py (1032B)
1 # IDEA: 2 3 # return the powerset of the set defined by the list of nums 4 # given that a mathematical set does not contain duplicate elements, 5 # we remove said duplicates by converting nums into a python set 6 # which contains has the same property 7 8 # we then recursively add or don't add any element at each step, 9 # returning a list of lists back up the stack and to the consumer 10 # of the method. 11 12 13 class Solution: 14 def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 15 nums.sort() 16 perms = recurse(nums, 0, []) 17 res = {str(str_perm): str_perm for str_perm in perms} 18 return list(res.values()) 19 20 21 def recurse(nums, index, current): 22 23 if index == len(nums): 24 return [current] 25 26 return_ls = [] 27 with_current = current.copy() 28 with_current.append(nums[index]) 29 30 res1 = recurse(nums, index + 1, with_current) 31 32 res2 = recurse(nums, index + 1, current) 33 34 for res in res2: 35 return_ls.append(res) 36 for res in res1: 37 return_ls.append(res) 38 39 return return_ls