主题:回溯
39. 组合总和
代码随想录代码随想录PDF,代码随想录网站,代码随想录百度网盘,代码随想录知识星球,代码随想录八股文PDF,代码随想录刷题路线,代码随想录知识星球八股文https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def backtrack(start, comb, curSum):
if curSum == target:
res.append(comb.copy())
return
if curSum > target:
return
for i in range(start, len(candidates)):
comb.append(candidates[i])
backtrack(i, comb, curSum + candidates[i])
comb.pop()
backtrack(0, [], 0)
return res
40.组合总和II
代码随想录代码随想录PDF,代码随想录网站,代码随想录百度网盘,代码随想录知识星球,代码随想录八股文PDF,代码随想录刷题路线,代码随想录知识星球八股文https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = []
def backtrack(start, comb, curSum):
if curSum > target: return
if curSum == target:
res.append(comb.copy())
return
prev = -1
for i in range(start, len(candidates)):
if prev == candidates[i]:
continue
comb.append(candidates[i])
backtrack(i + 1, comb, curSum + candidates[i])
comb.pop()
prev = candidates[i]
backtrack(0, [], 0)
return res
131.分割回文串
代码随想录代码随想录PDF,代码随想录网站,代码随想录百度网盘,代码随想录知识星球,代码随想录八股文PDF,代码随想录刷题路线,代码随想录知识星球八股文https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html
# check all the possible ways to partition the string
class Solution:
def isPali(self, s, l, r):
while l < r:
if s[l] != s[r]:
return False
l, r = l + 1, r - 1
return True
def partition(self, s: str) -> List[List[str]]:
res = []
part = []
def backtrack(i):
if i >= len(s):
res.append(part.copy())
return
for j in range(i, len(s)):
if self.isPali(s, i, j):
part.append(s[i:j+1])
backtrack(j+1)
part.pop()
backtrack(0)
return res