目录
78. 子集1
leetcode: 问题详情.
方法一、回溯法
class Solution(object):
def subsets(self, nums):
def backtracking(start_index, nums, path, res):
res.append(copy.deepcopy(path)) # 让[]也加入res
for i in range(start_index, len(nums)):
path.append(nums[i])
backtracking(i+1, nums, path, res)
path.pop()
if not nums:
return []
res = []
path = []
start_index = 0
backtracking(start_index, nums, path, res)
return res
90. 子集 II
leetcode: 问题详情.
方法一、回溯法+剪枝
class Solution(object):
def subsetsWithDup(self, nums):
def backtracking(start_index, res, path):
res.append(copy.deepcopy(path))
for i in range(start_index, len(nums)):
if i>start_index and nums[i] == nums[i-1]: # 剪枝
continue
path.append(nums[i])
backtracking(i+1, res, path)
path.pop()
start_index = 0
res = []
path = []
nums.sort()
backtracking(start_index, res, path)
return res