classSolution(object):
def subsets(self, nums):"""
:type nums: List[int]:rtype: List[List[int]]"""
# 1.扩展法,一个一个数扩展
result =[]
result.append([])for num in nums:
temp =[]for res in result:
r = res[:]
r.append(num)
temp.append(r)for t in temp:
result.append(t)return result
拓展法:逐个遍历,加到前面的子集中,看运行结果可知
classSolution(object):
def subsets(self, nums):"""
:type nums: List[int]:rtype: List[List[int]]"""
# 2.回溯法
result =[]
result.append([])
# 遍历数组的长度
for i in range(1,len(nums)+1):
self.backtracking(nums, result, i,0,[])return result
def backtracking(self, nums, result, length, index, subset):
# 先写中止条件
iflen(subset)== length:
temp = subset[:] # 避免引用传递
result.append(temp)return
# 不满足,就从数组中逐个遍历,一个一个找
for i in range(index,len(nums)):
# 逐个往子集中存,然后查看是否满足需要长度的条件,不满足的化,接下来继续进入backtracking中往下寻找,满足的话,就pop()出当前的,然后从下一个节点开始,再去寻找满足条件的子集
subset.append(nums[i])
self.backtracking(nums, result, length, i+1, subset)
# 满足,先pop(),然后从下一个节点开始找,也就是当前for循环中i的下一个节点
subset.pop()
回溯法:长度为0,1,2,3 看运行结果可知
classSolution(object):
def subsets(self, nums):"""
:type nums: List[int]:rtype: List[List[int]]"""
# 3.DFS
res =[]
self.dfs(nums, res,0,[])return res
def dfs(self, nums, res, index, subset):
# 每次dfs都会产生一个子集
temp = subset[:] # 避免引用传递
res.append(temp)
# 终止条件
if index ==len(nums):return
# 遍历整个数组,一直往下找,找到最后一个,就返回,从for循环的下一个点开始,
# 再接着往下找,再找到最后一个,停止,如次循环。
# 不撞南墙不回头找法
for i in range(index,len(nums)):
subset.append(nums[i])
self.dfs(nums, res, i+1, subset)
subset.pop()
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # 1.扩展法,一个一个数扩展 result = [] result.append([]) for num in nums: temp = [].