#solution where you just take subset I and replace last return statement
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
subset = []
result = []
#i is index of subset
def dfs(i):
if i >= len(nums):
result.append(subset.copy())
return
#decision to include nums[i]
subset.append(nums[i])
#this recursive call will be given filled subset
dfs(i + 1)
#decision NOT to include nums[i]
subset.pop()
#this recursive call will be given empty subset
dfs(i + 1)
dfs(0)
#need to remove duplicate sublists within result
return ([list(i) for i in {*[tuple(sorted(i)) for i in result]}])
#solution to prevent duplicates in the first place
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
def backtrack(i, subset):
if i == len(nums):
res.append(subset.copy())
return
#all subsets that include nums[i]
subset.append(nums[i])
backtrack(i + 1, subset)
#remove number we just added
subset.pop()
#all subsets that don't include nums[i]
while i + 1 < len(nums) and nums[i] == nums[i + 1]:
i += 1
backtrack(i + 1, subset)
backtrack(0, [])
return result
#solution for array with unique integer array. only last return line is dfferent
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
subset = []
result = []
#i is index of subset
def dfs(i):
if i >= len(nums):
result.append(subset.copy())
return
#decision to include nums[i]
subset.append(nums[i])
#this recursive call will be given filled subset
dfs(i + 1)
#decision NOT to include nums[i]
subset.pop()
#this recursive call will be given empty subset
dfs(i + 1)
dfs(0)
return result