今日任务
目录
39.组合总和 - Medium
题目链接:力扣-39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
提示:集合里元素可以用无数次,和组合问题的差别主要在于startIndex上的控制
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
path = []
def backtracking(candidates, target, startIndex, ttl):
if ttl == target and path not in result:
result.append(path[:])
return
if ttl > target or path in result:
return
for i in range(startIndex, len(candidates)):
path.append(candidates[i])
ttl += candidates[i]
backtracking(candidates, target, i, ttl)
path.pop()
ttl -= candidates[i]
backtracking(candidates, target, 0, 0)
return result
40.组合总和II - Medium
题目链接:力扣-40. 组合总和 II
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
提示:去重
class Solution:
def __init__(self):
self.result = []
self.path = []
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
self.backtracking(candidates, target, 0, 0)
return self.result
def backtracking(self, candidates, target, startIndex, ttl):
if ttl == target:
self.result.append(self.path[:])
return
if ttl > target:
return
for i in range(startIndex, len(candidates)):
if i >startIndex and candidates[i] == candidates[i-1]:
continue
self.path.append(candidates[i])
ttl += candidates[i]
self.backtracking(candidates, target, i+1, ttl)
self.path.pop()
ttl -= candidates[i]
131.分割回文串 - Medium
题目链接:力扣-131. 分割回文串
给你一个字符串
s
,请你将s
分割成一些子串,使每个子串都是 回文串 。返回s
所有可能的分割方案。回文串 是正着读和反着读都一样的字符串。
提示:字符串的切割回溯,倒置字符串判断是否为回文串
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
path = []
def backtracking(s, startIndex):
if startIndex >= len(s):
result.append(path[:])
return
for i in range(startIndex, len(s)):
temp = s[startIndex: i+1]
if temp == temp[::-1]:
path.append(s[startIndex: i+1])
backtracking(s, i+1)
path.pop()
else:
continue
backtracking(s, 0)
return result