程式碼隨想錄演算法訓練營第26天 | 回溯02:39. 組合總和、40.組合總和II、131.分割回文串
- 組合總和
https://leetcode.cn/problems/combination-sum/
程式碼隨想錄
https://programmercarl.com/0039.組合總和.html
40.組合總和II
https://leetcode.cn/problems/combination-sum-ii/description/
程式碼隨想錄
https://programmercarl.com/0040.組合總和II.html#演算法公開課
131.分割回文串
https://leetcode.cn/problems/palindrome-partitioning/description/
程式碼隨想錄
https://programmercarl.com/0131.分割回文串.html#其他語言版本
39. 組合總和
題解思路
題解程式碼:
class Solution:
def __init__(self):
self.res = []
self.path = []
def back_track(self,candidates,target,index):
if sum(self.path)>target:
return
if sum(self.path)==target:
self.res.append(self.path[:])
return self.res
for i in range(index,len(candidates)):
self.path.append(candidates[i])
self.back_track(candidates,target,i)
self.path.pop()
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
if len(candidates)==0:
return self.res
self.back_track(candidates,target,0)
return self.res
40.組合總和II
題解思路
- 不能重複
- 剪枝:
- 減去同一個樹層上重複的元素;
- 同一樹支上元素重複可以;
題解程式碼
class Solution:
def __init__(self):
self.res = []
self.path = []
def back_track(self,candidates,target,index):
if sum(self.path)==target:
if self.path not in self.res:
self.res.append(self.path[:])
return self.res
if sum(self.path)>target:
return
for i in range(index,len(candidates)):
if i>index and candidates[i]==candidates[i-1]:
continue
self.path.append(candidates[i])
self.back_track(candidates,target,i+1)
self.path.pop()
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
if len(candidates)==0:
return self.res
candidates = sorted(candidates)
self.back_track(candidates,target,0)
return self.res
131.分割回文串
題解思路
- 按位切割字串
- 判斷字串是否為迴文字串
- 最佳化也在判斷處
題解程式碼
class Solution:
def __init__(self):
self.curr = []
self.res = []
def panduan(self,s):
if s==s[::-1]:
return True
def back_trace(self,s,index):
if index==len(s):
self.res.append(self.curr[:])
return
for i in range(index+1,len(s)+1):
if self.panduan(s[index:i]):
self.curr.append(s[index:i])
self.back_trace(s,i)
self.curr.pop()
def partition(self, s: str) -> List[List[str]]:
if len(s)==0:
return self.res
self.back_trace(s,0)
return self.res