代码随想录刷题第二十七天| 39. 组合总和 ● 40.组合总和II ● 131.分割回文串
2023-12-31 08:15:08
代码随想录刷题第二十七天
组合总和 (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
文章来源:https://blog.csdn.net/shaozi25/article/details/135259552
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!