leetcode 39 组合总和
因为此题的题干要求可以不限元素的使用次数,因此需要调整startIndex
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
self.backtracking(candidates, target, 0, 0, [], result)
return result
def backtracking(self, candidates, target, total, startIndex, path, result):
if total > target:
return
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i, path, result)
total -= candidates[i]
path.pop()
leetcode 40 组合总和||
这题的关键是去重,暴力解法是想使用字典。正解是先对数组排序, 然后比较candiates[i] 和candiates[i-1] 在i > startIndex时。
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, total, startIndex, path, result):
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
# 去重操作
if startIndex < i and candidates[i] == candidates[i - 1]:
continue
if total > target:
break
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i + 1, path, result)
total -= candidates[i]
path.pop()
leetcode 131 分割回文串
终止条件这里刚开始没搞懂,
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
self.backtracking(s, 0, [], result)
return result
def backtracking(self, s, startIndex, path, result):
if startIndex == len(s):
result.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])
self.backtracking(s, i + 1, path, result)
path.pop()
354

被折叠的 条评论
为什么被折叠?



