代码随想录刷题第二十七天
组合总和 (LC 39)
题目思路:
代码实现:
class Solution:
def __init__(self):
self.result = []
self.path = []
self.sum = 0
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.backtracking(candidates, target, 0)
return self.result
def backtracking(self, candidates, target, start_index):
if self.sum > target:
return
if self.sum == target:
self.result.append(self.path[:])
return
for i in range(start_index, len(candidates)):
self.sum += candidates[i]
self.path.append(candidates[i])
self.backtracking(candidates, target, i)
self.path.pop()
self.sum -= candidates[i]
组合总和 II (LC 40) 去重,非常重要!!!
题目思路:
代码实现:
class Solution:
def __init__(self):
self.result = []
self.path = []
self.sum = 0
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
used = [0 for i in range(len(candidates))]
candidates.sort()
self.backtracking(candidates, target, 0, used)
return self.result
def backtracking(self, candidates, target, start_index, used):
if self.sum > target:
return
if self.sum == target:
self.result.append(self.path[:])
return
for i in range(start_index, len(candidates)):
if i>0 and candidates[i-1] == candidates[i] and used[i-1] == 0:
continue
self.sum += candidates[i]
self.path.append(candidates[i])
used[i] = 1
self.backtracking(candidates, target, i+1, used)
used[i] = 0
self.path.pop()
self.sum -= candidates[i]
分割回文串 (LC 131)
题目思路:
代码实现:
class Solution:
def __init__(self):
self.result = []
self.path = []
def partition(self, s: str) -> List[List[str]]:
self.backtracking(s, 0)
return self.result
def backtracking(self, s, startindex):
if startindex>=len(s):
self.result.append(self.path[:])
return
for i in range(startindex, len(s)):
if self.ishuiwen(s, startindex, i):
string = s[startindex:i+1]
self.path.append(string)
else:
continue
self.backtracking(s, i+1)
self.path.pop()
def ishuiwen(self, s, start, end):
i = start
j = end
while(i<j):
if s[i]!=s[j]:
return False
i+=1
j-=1
return True