39. 组合总和
对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def backtracking(total,startIndex,path):
if total > target:
return
if total==target:
res.append(path[:])
return
for i in range(startIndex,len(candidates)):
total+=candidates[i]
path.append(candidates[i])
backtracking(total,i,path)
total-=candidates[i]
path.pop()
res=[]
candidates.sort() #排序
backtracking(0,0,[])
return res
40.组合总和II
必须要去重,使用过的元素不能重复选取。要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。要去重记得要对数组排序。
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
def backtrack(total,startIndex,path):
if total>target:
return
if total==target:
res.append(path[:])
return
for i in range(startIndex,len(candidates)):
if i > startIndex and candidates[i] == candidates[i - 1]:
continue#在当前循环中,如果当前索引大于起始索引且当前数值与上一个数值相同,则直接跳过当前循环,继续下一次循环。
if total + candidates[i] > target:
break#在当前循环中,如果当前数值加上当前总和已经大于目标值,则直接跳出当前循环,避免继续递归下去,因为后续的数值只会更大,无法得到符合条件的组合。
total+=candidates[i]
path.append(candidates[i])
backtrack(total,i+1,path)
path.pop()
total-=candidates[i]
res=[]
path.clear()
res.clear()
backtrack(0,0,[])
return res
131.分割回文串
递归用来纵向遍历,for循环用来横向遍历,切割线(就是图中的红线)切割到字符串的结尾位置,说明找到了一个切割方法。
class Solution:
def partition(self, s: str) -> List[List[str]]:
def backtrack(startIndex,path):
if startIndex==len(s):
res.append(path[:])
return
for i in range(startIndex,len(s)):
if s[startIndex:i+1]==s[startIndex:i+1][::-1]:# 若反序和正序相同,意味着这是回文串
path.append(s[startIndex:i+1])
backtrack(i+1,path)# 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop()
res=[]
backtrack(0,[])
return res