给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
python:
class Solution:
def __init__(self):
self.path = []
self.ans = []
def backtrack(self, candidates, target, startindex, cur_sum):
if cur_sum == target:
self.ans.append(self.path[:])
if cur_sum > target:
return
for i in range(startindex, len(candidates)):
cur_sum += candidates[i]
self.path.append(candidates[i])
self.backtrack(candidates,target,i,cur_sum)
self.path.pop()
cur_sum -= candidates[i]
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.backtrack(candidates,target, 0, 0)
return self.ans
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
class Solution:
def __init__(self):
self.path = []
self.ans = []
def backtrack(self, candidates, target, startindex, cur_sum):
if cur_sum == target:
self.ans.append(self.path[:])
if cur_sum > target:
return
for i in range(startindex, len(candidates)):
if i > startindex and candidates[i] == candidates[i - 1]:
continue
cur_sum += candidates[i]
self.path.append(candidates[i])
self.backtrack(candidates,target,i + 1,cur_sum)
self.path.pop()
cur_sum -= candidates[i]
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
self.backtrack(candidates,target, 0, 0)
return self.ans
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
python:
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 ):
# 如果startIndex等于len(s),说明找到一个切割方法
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()