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 resultdef backtracking(self, candidates, target, startIndex, path, result, currentsum):if currentsum > target:returnif currentsum == target:result.append(path[:])returnfor 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 resultdef backtracking(self, candidates, target, currentsum, startIndex, path, result):if currentsum > target:returnif currentsum == target:result.append(path[:])returnfor i in range(startIndex, len(candidates)):if i > startIndex and candidates[i] == candidates[i-1]:continuecurrentsum += candidates[i]path.append(candidates[i])self.backtracking(candidates, target, currentsum, i+1, path, result)currentsum -= candidates[i]path.pop()
131.分割回文串
https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
class Solution:def partition(self, s: str) -> List[List[str]]:'''递归用于纵向遍历for循环用于横向遍历当切割线迭代至字符串末尾,说明找到一种方法类似组合问题,为了不重复切割同一位置,需要start_index来做标记下一轮递归的起始位置(切割线)'''result = []self.backtracking(s, 0, [], result)return resultdef backtracking(self, s, start_index, path, result ):# Base Caseif 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 = endwhile i < j:if s[i] != s[j]:return Falsei += 1j -= 1return True