39. 组合总和
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
results=[]
self.backward(candidates,target,0,results,[],0)
return results
#注意index从0开始
def backward(self,candidates,target,startindex,results,path,total):
if total>target:
return
if total==target:
results.append(path[:])
return
#注意return
for i in range(startindex,len(candidates)):
path.append(candidates[i])
total+=candidates[i]
self.backward(candidates,target,i,results,path,total)
total-=candidates[i]
path.pop()
40.组合总和II
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
results=[]
candidates.sort()
self.backward(candidates,target,0,results,[],0)
return results
#注意index从0开始
def backward(self,candidates,target,startindex,results,path,total):
if total==target:
results.append(path[:])
return
#注意return
for i in range(startindex,len(candidates)):
if i>startindex and candidates[i]==candidates[i-1]:
continue
if total+candidates[i]>target:
break
path.append(candidates[i])
total+=candidates[i]
self.backward(candidates,target,i+1,results,path,total)
total-=candidates[i]
path.pop()
131.分割回文串
给你一个字符串 s
,请你将 s
分割成一些 子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
子字符串 是字符串中连续的 非空 字符序列
回文 串是向前和向后读都相同的字符串。
class Solution:
def partition(self, s: str) -> List[List[str]]:
results=[]
self.backward(s,results,0,[])
return results
def backward(self,s,results,startindex,path):
if startindex==len(s):
results.append(path[:])
#path副本
return
for i in range(startindex,len(s)):
if self.huuh(s,startindex,i)==True:
path.append(s[startindex:i+1])
self.backward(s,results,i+1,path)
path.pop()
def huuh(self,s,start,end):
while start<end:
if s[start]!=s[end]:
return False
start+=1
end-=1
return True