原题
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Reference Answer
思路分析
解题思路:碰到这种问题,一律dfs。
此题设置了一个参数depth
用于辅助判断结束位置,
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
self.res = []
nums.sort()
self.dfs(nums, 0, 0, [])
return self.res
def dfs(self, nums, depth, start_index, temp_res):
self.res.append(temp_res)
if depth == len(nums):
return
for i in range(start_index, len(nums)):
self.dfs(nums, depth+1, i+1, temp_res + [nums[i]])
Note:
- 既想在python中直接完成回溯,list又没法直接用
list +count
,这里取个巧,使用list + [count]
代替,方法很巧妙(回溯法中不能在return 语句语句中用list.append(count)
,这种方式回溯不到添加count元素之前的状态,前面已经试验过很多次了,具体可参看本博客的 回溯法模型 一文)。 - 结合index,添加
depth
参数进行辅助回溯,很应景!