思路:每次回溯的时候同样的数字能被取到,所以更改一下startIndex即可
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.result = []
self.path = []
def backTracking(startIndex, candidates, target):
if sum(self.path) > target:
return
if sum(self.path) == target:
self.result.append(self.path[:])
return
for i in range(startIndex, len(candidates)):
self.path.append(candidates[i])
backTracking(i, candidates, target)
self.path.pop()
startIndex = 0
backTracking(startIndex, candidates, target)
return self.result
题目链接:40. 组合总和 II - 力扣(LeetCode)
思路:主要是要在树的宽度上去重,而树的高度上不用去重,需要用一个used数组来进行判断
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.result = []
self.path = []
self.used = [False] * len(candidates)
candidates.sort()
def backTracking(startIndex, candidates, target):
if sum(self.path) > target:
return
if sum(self.path) == target:
self.result.append(self.path[:])
return
for i in range(startIndex, len(candidates)):
if i > startIndex and candidates[i] == candidates[i - 1] and self.used[i - 1] == False:
continue
self.path.append(candidates[i])
self.used[i] = True
backTracking(i + 1, candidates, target)
self.used[i] = False
self.path.pop()
backTracking(0, candidates, target)
return self.result
题目链接:131. 分割回文串 - 力扣(LeetCode)
class Solution(object):
def isHuiWen(self,s , startIndex, end):
i = startIndex
j = end
while i < j:
if s[i] != s[j]:
return False
i = i + 1
j = j - 1
return True
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
self.result = []
self.path = []
def backTracking(startIndex):
if startIndex == len(s):
self.result.append(self.path[:])
return
#[aab]
for i in range(startIndex, len(s)):# 0, 1, 2 | 1, 2 | 2 | 3 == len(s) return
if self.isHuiWen(s, startIndex, i):# 0, 0 -> a | 1, 1-> a | 2, 2->b
self.path.append(s[startIndex : i+1]) # ["a"] ["a"] ["b"]
backTracking(i+1)
self.path.pop()
backTracking(0)
return self.result