第一题
进行排序,然后可以在for之后做一个剪枝
class Solution(object):
def __init__(self):
self.path=[]
self.res=[]
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
self.operation(candidates,target,0,0)
return self.res
def operation(self,candidates,target,total,startindex):
if total>target:
return
if total==target:
self.res.append(self.path[:])
return
for i in range(startindex,len(candidates)):
if total+candidates[i]>target:
break
total+=candidates[i]
self.path.append(candidates[i])
self.operation(candidates,target,total,i)
total-=candidates[i]
self.path.pop()
use数组,用来区分树层去重,还是树枝去重。
首先需要对数组进行排序
树层去重:数值=前一个数的数值,且前一个数没用过
树枝去重:正常
class Solution(object):
def __init__(self):
self.path=[]
self.res=[]
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.use=[0]*len(candidates)
candidates.sort()
self.operation(candidates,target,0,0)
return self.res
def operation(self,candidates,target,total,startindex):
if total>target:
return
if total==target:
self.res.append(self.path[:])
return
for i in range(startindex,len(candidates)):
if i>startindex and candidates[i]==candidates[i-1] and self.use[i-1]==0:
continue
if total + candidates[i] > target:
break
total+=candidates[i]
self.path.append(candidates[i])
self.use[i]=True
self.operation(candidates,target,total,i+1)
self.use[i]=False
total-=candidates[i]
self.path.pop()
第三题
把startindex看作隔板,从0位置开始
截止条件,startindex到了最后
回文字符串为s [ startindex : i ],满足条件进入后续代码(if 之后执行)
class Solution(object):
def __init__(self):
self.path=[]
self.res=[]
def partition(self, s):
self.operation(s,0)
return self.res
def operation(self,s,startindex):
if startindex==len(s):
self.res.append(self.path[:])
return
for i in range(startindex,len(s)):
if s[startindex:i+1]==s[startindex:i+1][::-1]:
self.path.append(s[startindex:i+1])
self.operation(s,i+1)
self.path.pop()