代码随想录算法训练营Day20 | Leetcode 39组合总和、40组合总和II、131分割回文串
一、组合总和
相关题目:Leetcode39
文档讲解:Leetcode39
视频讲解:Leetcode39
1. Leetcode39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
- 思路:
- 本题和 Leetcode77.组合,Leetcode216.组合总和III 的区别是:本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。搜索的过程抽象成树形结构如下:
- 回溯三部曲:
- 递归函数参数:
- 数组 result 存放结果集。
- path 存放符合条件的结果。
- 题目中给出的参数集合 candidates 和目标值 target。
- 定义 int 型的 sum 变量来统计单一结果 path 里的总和。
- startIndex 来控制 for 循环的起始位置。
- 递归终止条件:从叶子节点可以清晰看到,终止只有两种情况:
- sum 大于 target,直接终止。
- sum 等于 target,需要收集结果后终止。
- 单层搜索的逻辑:单层 for 循环从 startIndex 开始,搜索 candidates 集合。
- 递归函数参数:
- 剪枝优化:如果已经知道下一层的 sum 会大于 target,就没有必要进入下一层递归了。对总集合排序之后,如果下一层的 sum(就是本层的 sum + candidates[i])已经大于 target,就可以结束本轮 for 循环的遍历。
- 本题和 Leetcode77.组合,Leetcode216.组合总和III 的区别是:本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。搜索的过程抽象成树形结构如下:
- 回溯(版本一)
class Solution:
def backtracking(self, candidates, target, total, startIndex, path, result):
if total > target:
return
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i, path, result) # 不用i+1了,表示可以重复读取当前的数
total -= candidates[i]
path.pop()
def combinationSum(self, candidates, target):
result = []
self.backtracking(candidates, target, 0, 0, [], result)
return result
##回溯剪枝(版本一)
class Solution:
def backtracking(self, candidates, target, total, startIndex, path, result):
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
if total + candidates[i] > target:
break
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i, path, result)
total -= candidates[i]
path.pop()
def combinationSum(self, candidates, target):
result = []
candidates.sort() # 需要排序
self.backtracking(candidates, target, 0, 0, [], result)
return result
- 回溯(版本二)
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result =[]
self.backtracking(candidates, target, 0, [], result)
return result
def backtracking(self, candidates, target, startIndex, path, result):
if target == 0:
result.append(path[:])
return
if target < 0:
return
for i in range(startIndex, len(candidates)):
path.append(candidates[i])
self.backtracking(candidates, target - candidates[i], i, path, result)
path.pop()
##回溯剪枝(版本二)
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result =[]
candidates.sort()
self.backtracking(candidates, target, 0, [], result)
return result
def backtracking(self, candidates, target, startIndex, path, result):
if target == 0:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
if target - candidates[i] < 0:
break
path.append(candidates[i])
self.backtracking(candidates, target - candidates[i], i, path, result)
path.pop()
二、组合总和II
相关题目:Leetcode40
文档讲解:Leetcode40
视频讲解:Leetcode40
1. Leetcode40.组合总和II
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用 一次 。
注意: 所有数字(包括目标数)都是正整数。解集不能包含重复的组合。
- 思路:
- 这道题目和 Leetcode39.组合总和 如下区别:
- 本题 candidates 中的每个数字在每个组合中只能使用一次。
- 本题数组 candidates 的元素是有重复的,而 Leetcode39.组合总和 是无重复元素的数组 candidates。
- 难点在于集合(数组 candidates)有重复元素,但还不能有重复的组合。组合问题可以抽象为树形结构,那么“使用过”在这个树形结构上是有两个维度的:一个维度是同一树枝上使用过,一个维度是同一树层上使用过。我们所需要的去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。
- 回溯三部曲:
-
递归函数参数:
- 数组 result 存放结果集。
- path 存放符合条件的结果。
- 题目中给出的参数集合 candidates 和目标值 target。
- 定义 int 型的 sum 变量来统计单一结果 path 里的总和。
- startIndex 来控制 for 循环的起始位置。
- 此外,可以加一个 bool 型数组 used,用来记录同一树枝上的元素是否使用过(这里直接用 startIndex 来去重也是可以的, 就不用 used 数组了)。
-
递归终止条件:终止有两种情况:
- sum 大于 target,直接终止。
- sum 等于 target,需要收集结果后终止。
-
单层搜索的逻辑:单层 for 循环从 startIndex 开始,搜索 candidates 集合,此外需要对同一树层上的“使用过”的元素去重:如果 candidates[i] == candidates[i - 1] 并且 used[i - 1] == false,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过 candidates[i - 1]。此时 for 循环里就应该做 continue 的操作。
图中将 used 的变化用橘黄色标注上,可以看出在 candidates[i] == candidates[i - 1] 相同的情况下:- used[i - 1] == true,说明同一树枝 candidates[i - 1] 使用过。
- used[i - 1] == false,说明同一树层 candidates[i - 1] 使用过。
而 used[i - 1] == true,说明是进入下一层递归,去下一个数,所以是树枝上,如图所示:
-
- 这道题目和 Leetcode39.组合总和 如下区别:
- 回溯法
class Solution:
def backtracking(self, candidates, target, total, startIndex, path, result):
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
if i > startIndex and candidates[i] == candidates[i - 1]:
continue
if total + candidates[i] > target:
break
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i + 1, path, result)
total -= candidates[i]
path.pop()
def combinationSum2(self, candidates, target):
result = []
candidates.sort()
self.backtracking(candidates, target, 0, 0, [], result)
return result
- 回溯 使用used
class Solution:
def backtracking(self, candidates, target, total, startIndex, used, path, result):
if total == target:
result.append(path[:])
return
for i in range(startIndex, len(candidates)):
# 对于相同的数字,只选择第一个未被使用的数字,跳过其他相同数字
if i > startIndex and candidates[i] == candidates[i - 1] and not used[i - 1]:
continue
if total + candidates[i] > target:
break
total += candidates[i]
path.append(candidates[i])
used[i] = True
self.backtracking(candidates, target, total, i + 1, used, path, result)
used[i] = False
total -= candidates[i]
path.pop()
def combinationSum2(self, candidates, target):
used = [False] * len(candidates)
result = []
candidates.sort()
self.backtracking(candidates, target, 0, 0, used, [], result)
return result
- 回溯优化
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
results = []
self.combinationSumHelper(candidates, target, 0, [], results)
return results
def combinationSumHelper(self, candidates, target, index, path, results):
if target == 0:
results.append(path[:])
return
for i in range(index, len(candidates)):
if i > index and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > target:
break
path.append(candidates[i])
self.combinationSumHelper(candidates, target - candidates[i], i + 1, path, results)
path.pop()
三、分割回文串
相关题目:Leetcode131
文档讲解:Leetcode131
视频讲解:Leetcode131
1. Leetcode131.分割回文串
给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
-
思路:
-
涉及到两个关键问题:
- 切割问题,有不同的切割方式。
- 判断回文。
切割问题也像组合问题一样可以抽象为一棵树形结构:
-
回溯三部曲:
- 递归函数参数:全局变量数组 path 存放切割后回文的子串,二维数组 result 存放结果集(这两个参数可以放到函数参数里),本题递归函数参数还需要 startIndex,因为切割过的地方,不能重复切割,和组合问题也是保持一致的。
- 递归函数终止条件:从树形结构的图中可以看出,切割线切到了字符串最后面,说明找到了一种切割方法,此时就是本层递归的终止条件。
- 单层搜索的逻辑:在 for 循环中,我们 定义了起始位置 startIndex,那么 [startIndex, i] 就是要截取的子串。首先判断这个子串是不是回文,如果是回文,就加入在 path 中,path 用来记录切割过的回文子串。
-
判断回文子串:可以使用双指针法,一个指针从前向后,一个指针从后向前,如果前后指针所指向的元素是相等的,就是回文字符串了。
-
主要难点:
- 切割问题可以抽象为组合问题
- 如何模拟那些切割线
- 切割问题中递归如何终止
- 在递归循环中如何截取子串
- 如何判断回文
-
-
回溯+判断回文
class Solution:
def partition(self, s: str) -> List[List[str]]:
'''
递归用于纵向遍历
for循环用于横向遍历
当切割线迭代至字符串末尾,说明找到一种方法
类似组合问题,为了不重复切割同一位置,需要start_index来做标记下一轮递归的起始位置(切割线)
'''
result = []
self.backtracking(s, 0, [], result)
return result
def backtracking(self, s, start_index, path, result ):
# Base Case
if start_index == len(s):
result.append(path[:])
return
# 单层递归逻辑
for i in range(start_index, len(s)):
# 此次比其他组合题目多了一步判断:
# 判断被截取的这一段子串([start_index, i])是否为回文串
if self.is_palindrome(s, start_index, i):
path.append(s[start_index:i+1])
self.backtracking(s, i+1, path, result) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop() # 回溯
def is_palindrome(self, s: str, start: int, end: int) -> bool:
i: int = start
j: int = end
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
##回溯+优化判定回文函数
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
self.backtracking(s, 0, [], result)
return result
def backtracking(self, s, start_index, path, result ):
# Base Case
if start_index == len(s):
result.append(path[:])
return
# 单层递归逻辑
for i in range(start_index, len(s)):
# 若反序和正序相同,意味着这是回文串
if s[start_index: i + 1] == s[start_index: i + 1][::-1]:
path.append(s[start_index:i+1])
self.backtracking(s, i+1, path, result) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop() # 回溯
##回溯+高效判断回文子串
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
isPalindrome = [[False] * len(s) for _ in range(len(s))] # 初始化isPalindrome矩阵
self.computePalindrome(s, isPalindrome)
self.backtracking(s, 0, [], result, isPalindrome)
return result
def backtracking(self, s, startIndex, path, result, isPalindrome):
if startIndex >= len(s):
result.append(path[:])
return
for i in range(startIndex, len(s)):
if isPalindrome[startIndex][i]: # 是回文子串
substring = s[startIndex:i + 1]
path.append(substring)
self.backtracking(s, i + 1, path, result, isPalindrome) # 寻找i+1为起始位置的子串
path.pop() # 回溯过程,弹出本次已经添加的子串
def computePalindrome(self, s, isPalindrome):
for i in range(len(s) - 1, -1, -1): # 需要倒序计算,保证在i行时,i+1行已经计算好了
for j in range(i, len(s)):
if j == i:
isPalindrome[i][j] = True
elif j - i == 1:
isPalindrome[i][j] = (s[i] == s[j])
else:
isPalindrome[i][j] = (s[i] == s[j] and isPalindrome[i+1][j-1])
##回溯+使用all函数判断回文子串
class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
self.partition_helper(s, 0, [], result)
return result
def partition_helper(self, s, start_index, path, result):
if start_index == len(s):
result.append(path[:])
return
for i in range(start_index + 1, len(s) + 1):
sub = s[start_index:i]
if self.isPalindrome(sub):
path.append(sub)
self.partition_helper(s, i, path, result)
path.pop()
def isPalindrome(self, s):
return all(s[i] == s[len(s) - 1 - i] for i in range(len(s) // 2))