一、继续刷回溯题目:
1.leetcode题目 39. 组合总和 - 力扣(LeetCode)
解决:
我画了一个丑丑的图:
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
cur_sum = 0
combination = []
result = []
def dfs(candidates,target,cur_sum,combination,result,s_index):
if cur_sum == target:
result.append(combination[:])
return
if cur_sum > target:
return
else:
for i in range(s_index,len(candidates)):
cur_sum += candidates[i]
combination.append(candidates[i])
dfs(candidates,target,cur_sum,combination,result,i)
cur_sum -= candidates[i]
combination.pop()
dfs(candidates,target,cur_sum,combination,result,0)
return result
2.leetcode题目 40. 组合总和 II - 力扣(LeetCode)
想清楚上一道题目这题就很轻松了
刚开始写了个错误版本:(没有看见candidates有重复字符串)
class Solution:
###没有对candidates中的数据排序 以及去重剪枝
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(candidates,target,combination,result,cur_sum,s_index):
if cur_sum == target:
result.append(combination[:])
return
if cur_sum > target:
return
else:
for i in range(s_index,len(candidates)):
cur_sum += candidates[i]
combination.append(candidates[i])
dfs(candidates,target,combination,result,cur_sum,i+1)
cur_sum -= candidates[i]
combination.pop()
result = []
dfs(candidates,target,[],result,0,0)
return result
正确版本:
class Solution:
###没有对candidates中的数据排序 以及去重剪枝
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(candidates,target,combination,result,cur_sum,s_index):
if cur_sum == target:
result.append(combination[:])
return
if cur_sum > target:
return
else:
for i in range(s_index,len(candidates)):
if i>s_index and candidates[i] == candidates[i-1]:
continue
cur_sum += candidates[i]
combination.append(candidates[i])
dfs(candidates,target,combination,result,cur_sum,i+1)
cur_sum -= candidates[i]
combination.pop()
result = []
candidates.sort()
dfs(candidates,target,[],result,0,0)
return result
3.leetcode题目 131. 分割回文串 - 力扣(LeetCode)
切割问题其实是一种组合问题??
又画了一个丑丑的图:
解决:
class Solution:
def partition(self, s: str) -> List[List[str]]:
def is_huiwenchuan(s):
return all(s[i] == s[len(s) - i -1] for i in range(len(s)//2))
def dfs(s,s_index,result,path):
if s_index == len(s):
result.append(path[:])
return
for i in range(s_index,len(s)):
if is_huiwenchuan(s[s_index:i+1]):
path.append(s[s_index:i+1])
dfs(s,i+1,result,path)
path.pop()
result = []
dfs(s,0,result,[])
return result