class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans = []
cur = []
def dfs(i):
if i == len(nums):
ans.append(cur.copy())
return
# 包括 nums[i]
cur.append(nums[i])
dfs(i+1)
# 不包括 nums[i]
cur.pop()
dfs(i+1)
dfs(0)
return ans
要找出所有子集,对于数组里的每个元素,都只有选或不选两种情况,所以从下标 i = 0 开始,包括或不包括 nums[i],然后对下一个位置 i + 1 进行同样操作。由于 cur 数组是会变的,所以要 copy 或者 cur[:]
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans = []
cur = []
def dfs(start):
if len(cur) == k:
ans.append(cur.copy())
return
if start > n:
return
for i in range(start, n + 1):
cur.append(i)
dfs(i + 1)
cur.pop()
dfs(1)
return ans
对于组合,考虑了数字 i,后面添加的数要大于 i
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
cur = []
def dfs(i, total):
if total == target:
ans.append(cur.copy())
return
if i >= len(candidates) or total > target:
return
cur.append(candidates[i])
dfs(i, total + candidates[i])
cur.pop()
dfs(i + 1, total)
dfs(0, 0)
return ans
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ans = []
cur = []
counter = collections.Counter(nums)
def dfs():
if len(cur) == len(nums):
ans.append(cur.copy())
return
for i in counter:
if counter[i] > 0:
cur.append(i)
counter[i] -= 1
dfs()
cur.pop()
counter[i] += 1
dfs()
return ans
排列从思路上是逐个添加,但是代码实现上要用逐个排除的方法。
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
ans = []
cur = []
nums.sort()
def dfs(i):
if i == len(nums):
ans.append(cur.copy())
return
cur.append(nums[i])
dfs(i+1)
cur.pop()
while i + 1 < len(nums) and nums[i] == nums[i + 1]:
i += 1
dfs(i+1)
dfs(0)
return ans
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
ans = []
cur = []
def dfs(pos, total):
if total == target:
ans.append(cur.copy())
return
if pos >= len(candidates) or total > target:
return
pre = -1
for i in range(pos, len(candidates)):
if candidates[i] == pre:
continue
cur.append(candidates[i])
dfs(i + 1, total + candidates[i])
cur.pop()
pre = candidates[i]
dfs(0, 0)
return ans
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
ans = []
cur = []
counter = collections.Counter(nums)
def dfs():
if len(cur) == len(nums):
ans.append(cur.copy())
return
for i in counter:
if counter[i] > 0:
cur.append(i)
counter[i] -= 1
dfs()
cur.pop()
counter[i] += 1
dfs()
return ans