131:分割回文串
这题有点难,对于我的那个难点,一个是应该是不知道递归的逻辑写在哪里,看了题解和视频讲解才明白,原来,如果不是回文串就不进行接下来的递归操作了。第二个是分割,在这个题目中,索引是统一的,不要想着传进去一个局部串,然后在搞局部索引那些,会很麻烦。start索引跟for循环配合着,整个代码写下来是一致的。每做一次递归,就是在上一层的结果上再继续分割一次。
每进行一次分割就是就行一次递归的逻辑,每一个横行,就是一个for循环的逻辑。这个题用回溯法,记得一定要有回溯操作,紧跟在递归之后。
class Solution:
def isP(self,s,start,end):
while(start<end):
if s[start]==s[end]:
start+=1
end-=1
else:
return False
return True
def partition(self,s):
res=[]
path=[]
startindex=0
ss=list(s)
def Traversal(str,startindex,path):
if startindex==len(s):
res.append(path[:])
return
for i in range(startindex,len(ss)):
if self.isP(s,startindex,i):
path.append(s[startindex:i+1])
Traversal(s,i+1,path)
path.pop()
else:
continue
Traversal(s,startindex,path)
return res
t=Solution()
s="aab"
result=t.partition(s)
print(result)
39:组合总和
一开始忘记加startindex,导致最后输出的结果,有很多重复的,所以,从这一点体会到startindex的重要性!
class Solution:
def combinationSum(self,candidates,target):
path=[]
res=[]
start_index=0
def tarversal(start_index,candidates,target,sum_):
if sum_>target:
return
elif sum_==target:
res.append(path[:])
return
for i in range(start_index,len(candidates)):
sum_=sum_+candidates[i]
path.append(candidates[i])
tarversal(i,candidates,target,sum_)
sum_=sum_-candidates[i]
path.pop()
tarversal(start_index,candidates,target,0)
return res
t=Solution()
candidates=[2,3,6,7]
target=7
result=t.combinationSum(candidates,target)
print(result)
这个题是二刷了,这次自己写一遍,整体是知道怎么写了,但是有一个地方还是卡住了,一开始设计的是用一个使用减法,减到0,但是自己写的有点走火入魔了,没写出来。最后还是尝试设定一个变量sum_,然后每次做一个递归,就让他加到target,然后输出。思路就比较清晰了。算是有进步,虽然进步的不多。这次写了一个没有剪枝的,并没有对candidates进行排序。因为今天有点累,哈哈!
40:组合总和2
这个题跟上一个题不同的是,不用重复的的数字(注意是相同索引的),这好办,直接每次递归的时候startIndex=i+1,就好了。关键是还有一个与上题不同的一点就是,这次的数组是带有重复数字的,上一个题是不带有重复数字的,所以呢,需要去重!去重的话,在三数之和那里讲的去重方法就很经典,那就是if i>0 and candidates[i]==candidates[i-1]:continue
当然这么做的一个大前提就是,事先要给candidates排好序噢:
class Solution:
def combinationSum2(self,candidates,target):
path=[]
res=[]
sum_=0
startIndex=0
candidates.sort()
def Traversal(candidates,target,sum_,startIndex):
if sum_==target:
res.append(path[:])
return
elif sum_>target:
return
for i in range(startIndex,len(candidates)):
if i>startIndex and candidates[i]==candidates[i-1]:
continue
sum_=sum_+candidates[i]
path.append(candidates[i])
Traversal(candidates,target,sum_,i+1)
sum_=sum_-candidates[i]
path.pop()
Traversal(candidates,target,0,startIndex)
return res
candidates=[10,1,2,7,6,1,5]
target=8
t=Solution()
result=t.combinationSum2(candidates,target)
print(result)
这个题也是二刷了,自己一开始写的时候,没有去重,导致有很多相同的,所以,看了题解之后,才想起来要用三数之和里面的方法去重是最有效的!看来自己的去重大法还没有练好啊!第一反应就然没有想起来,还是刷题刷的不够多呀!