39. Combination Sum ![](https://i-blog.csdnimg.cn/blog_migrate/275f5a6a95d426693433d0a69720fc3b.png)
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
self.backtracking(candidates,[], target,0, result)
return result
def backtracking(self, candidates, path, target, s, result):
if s == target:
result.append(path[:])
return
if s > target:
return
for i in range(len(candidates)):
path.append(candidates[i])
s += candidates[i]
self.backtracking(candidates[i:], path, target, s, result)
s -= candidates[i]
path.pop()
40. Combination Sum II
去重:树层去重(yes)和树枝去重 (no)
用used来标记,如果前后两个元素相等且前面一个元素没用过,就可以剪枝
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
used = [False] * len(candidates)
result = []
candidates.sort()
self.backtracking(0,candidates,used, target, 0, [], result)
return result
def backtracking(self, s, candidates, used, target, startIndex, path, result):
if s == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
if i > startIndex and candidates[i] == candidates[i-1] and not used[-1]:
continue
if s + candidates[i]>target:
break
s += candidates[i]
path.append(candidates[i])
used[i] = True
self.backtracking(s, candidates, used, target, i+1,path, result)
path.pop()
s -= candidates[i]
used[i] = False
131. Palindrome Partitioning
startIndex是切割线
从startindex到i是被切割的子串
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
result = []
self.backtracking(s, 0, [], result)
return result
def backtracking(self,s, startIndex, path, result):
if startIndex == len(s):
result.append(path[:])
return
for i in range(startIndex,len(s)):
if self.is_palindrome(s,startIndex,i):
path.append(s[startIndex:i+1])
self.backtracking(s, i+1, path, result) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop()
def is_palindrome(self, s, start, end):
i= start
j= end
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True