39. 组合总和
题目链接/文章讲解:代码随想录
分析:因为元素可以重复出现,故回溯过程中可以从当前元素开始
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
tmp = []
def backtracing(candidates,index):
if sum(tmp) == target:
res.append(tmp[:])
return
if sum(tmp) > target:
return
for i in range(index,len(candidates)):
tmp.append(candidates[i])
backtracing(candidates,i)
tmp.pop()
backtracing(candidates,0)
return res
40.组合总和II
题目链接/文章讲解:代码随想录
分析:因为candidate中每个数字在每个组合中只能出现一次,即每个数字只能使用一次,不能重复使用
class Solution:
def backtracking(self, candidates, target, total, startIndex, used, path, result):
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
# 对于相同的数字,只选择第一个未被使用的数字,跳过其他相同数字
if i > startIndex and candidates[i] == candidates[i - 1] and not used[i - 1]:
continue
if total + candidates[i] > target:
break
total += candidates[i]
path.append(candidates[i])
used[i] = True
self.backtracking(candidates, target, total, i + 1, used, path, result)
used[i] = False
total -= candidates[i]
path.pop()
def combinationSum2(self, candidates, target):
used = [False] * len(candidates)
result = []
candidates.sort()
self.backtracking(candidates, target, 0, 0, used, [], result)
return result
131.分割回文串
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
self.backtracking(s, 0, [], result)
return result
def backtracking(self, s, start_index, path, result ):
# Base Case
if start_index == len(s):
result.append(path[:])
return
# 单层递归逻辑
for i in range(start_index, len(s)):
# 若反序和正序相同,意味着这是回文串
if s[start_index: i + 1] == s[start_index: i + 1][::-1]:
path.append(s[start_index:i+1])
self.backtracking(s, i+1, path, result) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop() # 回溯