给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

解法一:回溯

需要先排序,在for循环中需要跳过重复元素以避免相同的path。

  1. class Solution:
  2. def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
  3. res, n = [], len(nums)
  4. nums.sort()
  5. def dfs(start, path):
  6. res.append([*path])
  7. for i in range(start, n):
  8. if i > start and nums[i] == nums[i - 1]:
  9. continue
  10. path.append(nums[i])
  11. dfs(i + 1, path)
  12. path.pop()
  13. dfs(0, [])
  14. return res