39. 组合总和
https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
self.backtracking(candidates, target,0, [], result,0)
return result
def backtracking(self, candidates, target, startIndex, path, result, currentsum):
if currentsum > target:
return
if currentsum == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
currentsum += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, i, path, result, currentsum)
currentsum -= candidates[i]
path.pop()
40.组合总和II
https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
candidates.sort()
self.backtracking(candidates, target, 0, 0, [], result)
return result
def backtracking(self, candidates, target, currentsum, startIndex, path, result):
if currentsum > target:
return
if currentsum == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
if i > startIndex and candidates[i] == candidates[i-1]:
continue
currentsum += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, currentsum, i+1, path, result)
currentsum -= candidates[i]
path.pop()
131.分割回文串
class Solution:
def partition(self, s: str) -> List[List[str]]:
'''
递归用于纵向遍历
for循环用于横向遍历
当切割线迭代至字符串末尾,说明找到一种方法
类似组合问题,为了不重复切割同一位置,需要start_index来做标记下一轮递归的起始位置(切割线)
'''
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)):
# 此次比其他组合题目多了一步判断:
# 判断被截取的这一段子串([start_index, i])是否为回文串
if self.is_palindrome(s, start_index, i):
path.append(s[start_index:i+1])
self.backtracking(s, i+1, path, result) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop() # 回溯
def is_palindrome(self, s: str, start: int, end: int) -> bool:
i: int = start
j: int = end
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True