class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.res = []
tmpList = []
for i in range(len(nums)+1): #len+1轮循环,每次输出长度为i的所有组合
self.backtrack(nums, tmpList, i, 0)
return self.res
def backtrack(self, nums, tmpList, k, start):
if len(tmpList) == k:
self.res.append(list(tmpList))
else:
for i in range(start, len(nums)):
#经典回溯格式
tmpList.append(nums[i])
self.backtrack(nums, tmpList, k, i + 1)
tmpList.pop()
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.res = []
tmpList = []
for i in range(len(nums)+1): #len+1轮循环,每次输出长度为i的所有组合
self.backtrack(nums, tmpList, i, 0)
return self.res
def backtrack(self, nums, tmpList, k, start):
if len(tmpList) == k:
self.res.append(list(tmpList))
else:
for i in range(start, len(nums)):
#tmp的修改直接写在递归里
self.backtrack(nums, tmpList+[nums[i]], k, i + 1)
self.backtrack(nums, tmpList.append([nums[i]]), k, i + 1)