1 问题
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
2 答案
自己写的,根据上一题,回溯算法,再套个for循环就可以
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(start, depth, path, res, k):
if depth == k: # 也可以不设最大深度,直接append,因为要所有子集,参考官方解3
res.append(path)
return
for index in range(start, len(nums)):
dfs(index+1, depth+1, path+[nums[index]], res, k)
res = []
for i in range(len(nums)+1):
dfs(0, 0, [], res, i)
return res
官方解
- itertools 库函数
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
for i in range(len(nums)+1):
for tmp in itertools.combinations(nums, i):
res.append(tmp)
return res
- 迭代
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for i in nums:
res += [[i] + num for num in res] # 新遍历的和res中已经存在的每一个元素连接,并存储在res中
return res
- 递归(回溯算法),思路相同,更简洁
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
def dfs(start, path):
res.append(path)
for index in range(start, n):
dfs(index+1, path+[nums[index]]) # 在这里index+1
dfs(0, [])
return res
https://leetcode.cn/problems/subsets/solutions/6899/hui-su-suan-fa-by-powcai-5/
- 输入的视角(选或不选)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans = []
path = []
n = len(nums)
def dfs(i):
if i == n:
ans.append(path.copy())
return
dfs(i+1)
path.append(nums[i])
dfs(i+1)
path.pop()
dfs(0)
return ans
- 答案的视角(选哪个数)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans = []
path = []
n = len(nums)
def dfs(i):
ans.append(path.copy())
if i == n: # 这两行也可以不写
return #
for j in range(i, n):
path.append(nums[j])
dfs(j+1)
path.pop()
dfs(0)
return ans
https://leetcode.cn/problems/subsets/solutions/2059409/hui-su-bu-hui-xie-tao-lu-zai-ci-pythonja-8tkl