39. 组合总和
难度:☆3
a. 递归法+回溯
如果是一个集合来求组合,需要 startIndex
;如果是多个集合求组合,各个集合之间互不影响,则不需要 startIndex
。
- 回溯过程完全显式,初步剪枝。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
path = []
result = []
def backtrack(candidates: List[int], target: int, total: int, startIndex: int) -> None:
if total > target: # 剪枝
return
if total == target: # 找到符合要求的组合
result.append(path.copy()) # 硬拷贝
return
for i in range(startIndex, len(candidates)):
total += candidates[i] # 处理
path.append(candidates[i]) # 处理
backtrack(candidates, target, total, i) # 递归
total -= candidates[i] # 回溯
path.pop() # 回溯
backtrack(candidates, target, 0, 0)
return result
- 回溯过程部分显式,排序之后,深入剪枝。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
path = []
result = []
candidates.sort() # 排序
def backtrack(candidates: List[int], target: int, total: int, startIndex: int) -> None:
if total == target: # 找到符合要求的组合
result.append(path.copy()) # 硬拷贝
return
for i in range(startIndex, len(candidates)):
if total + candidates[i] > target: # 剪枝
break
path.append(candidates[i]) # 处理
backtrack(candidates, target, total+candidates[i] , i) # 递归隐藏回溯
path.pop() # 回溯
backtrack(candidates, target, 0, 0)
return result
40. 组合总和 II
难度:☆
131. 分割回文串
难度:☆