给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
解法一:回溯
需要先排序,在for循环中需要跳过重复元素以避免相同的path。
class Solution:def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:res, n = [], len(nums)nums.sort()def dfs(start, path):res.append([*path])for i in range(start, n):if i > start and nums[i] == nums[i - 1]:continuepath.append(nums[i])dfs(i + 1, path)path.pop()dfs(0, [])return res
