39. 组合总和
这道题可以重复选取元素,所以在递归的时候就不需要从i+1开始了
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.backreacking(0, [], res, candidates, target)
return res
def backreacking(self, startindex, path, res, candidates, target):
if sum(path) > target: # 元素的和大于目标了就返回,等于目标了就加入res
return
if sum(path) == target:
res.append(path[:])
return
for i in range(startindex, len(candidates)):
if sum(path)+candidates[i] > target: # 剪枝,若此时和已经大于target了,则没有必要进入下一层递归了
continue
path.append(candidates[i])
self.backreacking(i, path, res, candidates, target)
path.pop()
40.组合总和II
本题和上一题的区别在于,本题中candidates中元素里有重复;本题中candidates里每个元素只能用一次。同时和上一题一样结果中没有重复的。因此要去重
其实就是树枝上可以有重复元素(因为都是同一个组合里的),但是树层上不能有使用过的元素。
所以引入一个used来记录每一个元素是否被用过
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
used = [False]*len(candidates)
res = []
self.backtracking(candidates, target, 0, 0, used, [], res)
return res
def backtracking(self, candidates, target, currentsum, startindex, used, path, res):
if currentsum == target:
res.append(path[:])
return
for i in range(startindex, len(candidates)):
if i > 0 and candidates[i] == candidates[i-1] and used[i-1] == False: # 这里的意思是,在树层上重复取过的就不要再取了,used[i-1] == False是用来说明树枝上如果取过了后面还有相同元素的话可以再取
continue
if candidates[i] + currentsum > target:
break
currentsum += candidates[i]
path.append(candidates[i])
used[i] = True
self.backtracking(candidates, target, currentsum, i+1, used, path, res)
used[i] = False
currentsum -= candidates[i]
path.pop()
131.分割回文串
有点难
要想清楚其实startindex(下一轮递归遍历的起始位置)就是分割线,然后就是加一层回文串的判断
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.backtracking(s, 0, [], res)
return res
def is_huiwen(self, s):
if s != [] and s == s[::-1]:
return True
return False
def backtracking(self, s, startindex, path, res):
if startindex >= len(s):
res.append(path[:])
return
for i in range(startindex, len(s)):
if self.is_huiwen(s[startindex:i+1]):
path.append(s[startindex:i+1])
self.backtracking(s, i+1, path, res)
path.pop()