class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() def dfs(path, index): if path not in res: res.append(path) for i in range(index, len(nums)): if i > index and nums[i] == nums[i-1]: continue dfs(path+[nums[i]], i+1) dfs([], 0) return res
也有更简单的方法
1 2 3 4 5 6 7 8 9 10 11
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [[]] nums.sort() for num in nums: for i in range(len(res)): if res[i] + [num] not in res: res.append(res[i]+[num]) return res