78. Subsets
Description
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Idea
经典dfs问题, 因为nums里的值是unique的,而且对于返回的结果没有排序要求所以不需要用sort
Code
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
res = []
self.dfs(nums, 0, [], res)
return res
# 从index数开始,寻找已curr为开始的所有子集
def dfs(self, nums, index, curr, res):
#因为是求全组合,所以所有的curr都需要加到res
# 因为curr一直是一个reference,所以要深度copy。新生成一个curr加到res里
res.append(list(curr))
for i in range(index, len(nums)):
#把元素 i 加到curr,继续找接下里的子集
curr.append(nums[i])
self.dfs(nums, i + 1, curr, res)
# 把 i pop掉, 继续看下一个元素
curr.pop()