给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解法一:迭代法

初始化一个包含空集的结果集,然后遍历nums,用nums不断拓展已有的集合。

  1. class Solution:
  2. def subsets(self, nums: List[int]) -> List[List[int]]:
  3. res = [[]]
  4. for num in nums:
  5. for i in range(len(res)):
  6. res.append(res[i] + [num])
  7. return res

解法二:回溯

按子集的长度逐层递归回溯,root为空集,第n层为长度为n-1个元素构成的子集。

  1. class Solution:
  2. def subsets(self, nums: List[int]) -> List[List[int]]:
  3. """Build subsets with length 0, 1...len(nums)."""
  4. res = []
  5. for i in range(len(nums)):
  6. self.bc(nums, i, 0, [], res)
  7. return res
  8. def bc(self, nums, length, start, cur, res):
  9. """
  10. Use backtracking to build subsets of nums.
  11. Args:
  12. nums (List[int]): the provided number list
  13. length (int): the target length of the current subset
  14. start (int): the index of the first number of the subset in nums
  15. cur (List[int]): the current subset
  16. res (List[int]): the result list
  17. Returns:
  18. None
  19. """
  20. if len(cur) == length:
  21. res.append(cur[:])
  22. return
  23. for i in range(start, len(nums)):
  24. cur.append(nums[i])
  25. self.bc(nums, length, i + 1, cur, res)
  26. cur.pop()

解法三:DFS

从第一个元素开始深度遍历,将经过的路径保存。当前层的下一步只能访问当前元素后面的元素。

  1. class Solution:
  2. def subsets(self, nums: List[int]) -> List[List[int]]:
  3. res, n = [], len(nums)
  4. def dfs(start, path):
  5. res.append(path)
  6. for i in range(start, n):
  7. dfs(i + 1, path + [nums[i]])
  8. dfs(0, [])
  9. return res