代码随想录训练营 Day23打卡 回溯算法part02 39. 组合总和 40. 组合总和II 131. 分割回文串

代码随想录训练营 Day23打卡 回溯算法part02

一、 力扣39. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 :
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

本题搜索的过程抽象成树形结构如下:
在这里插入图片描述
注意图中叶子节点的返回条件,因为本题没有组合数量要求,仅仅是总和的限制,所以递归没有层数的限制,只要选取的元素总和超过target,就返回!

版本一 回溯

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)  # 递归调用,注意起始索引不变
            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

力扣题目链接
题目文章讲解
题目视频讲解

二、 力扣40. 组合总和II

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次
注意:解集不能包含重复的组合。
示例 :
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

这道题目和39.组合总和 (opens new window)如下区别:

  1. 本题candidates 中的每个数字在每个组合中只能使用一次。
  2. 本题数组candidates的元素是有重复的,而39.组合总和 (opens new
    window)是无重复元素的数组candidates

最后本题和39.组合总和 (opens new window)要求一样,解集不能包含重复的组合。

本题的难点在于区别2中:集合(数组candidates)有重复元素,但还不能有重复的组合。

选择过程树形结构如图所示:
在这里插入图片描述

版本一 回溯

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()  # 回溯,从路径中移除最后一个元素

力扣题目链接
题目文章讲解
题目视频讲解

三、 力扣131. 分割回文串

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
示例
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]

切割问题,也可以抽象为一棵树形结构,如图:
在这里插入图片描述

版本一 回溯

  1. 初始化和启动回溯:

    在 partition 方法中,初始化一个空的结果集 result。
    调用 backtracking 方法开始回溯过程。

  2. 回溯函数 backtracking:

    如果当前起始索引 start_index 等于字符串长度,表示找到一种分割方法,将当前路径加入结果集。
    否则,从当前起始索引开始遍历字符串的每个子串:
        检查子串是否为回文。
        如果是回文,将子串加入路径,递归处理剩余字符串。
        回溯时移除最后加入的子串,恢复状态。

  3. 判断回文函数 is_palindrome:

    逐字符比较子串的两端,判断其是否为回文。

from typing import List

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 = start        
        j = end
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True 

版本二 回溯(优化)

  1. 初始化和启动回溯:

    在 partition 方法中,初始化一个空的结果集 result。
    调用 backtracking 方法开始回溯过程。

  2. 回溯函数 backtracking:

    如果当前起始索引 start_index 等于字符串长度,表示找到一种分割方法,将当前路径加入结果集。
    否则,从当前起始索引开始遍历字符串的每个子串:
        检查子串是否为回文。
        如果是回文,将子串加入路径,递归处理剩余字符串。
        回溯时移除最后加入的子串,恢复状态。

  3. 判断回文:

    直接通过切片和反转字符串来判断子串是否为回文。

from typing import List

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 ):
        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()  # 回溯

版本三 高效判断回文子串

  1. 初始化和启动回溯:

    在 partition 方法中,初始化一个布尔矩阵 isPalindrome,用于记录子串是否为回文。
    调用 computePalindrome 预处理所有子串,填充 isPalindrome 矩阵。
    调用 backtracking 方法开始回溯过程。

  2. 回溯函数 backtracking:

    如果当前起始索引 startIndex 等于字符串长度,表示找到一种分割方法,将当前路径加入结果集。
    否则,从当前起始索引开始遍历字符串的每个子串:
        检查子串是否为回文(通过 isPalindrome 矩阵)。
        如果是回文,将子串加入路径,递归处理剩余字符串。
        回溯时移除最后加入的子串,恢复状态。

  3. 预处理回文子串:

    使用动态规划填充 isPalindrome 矩阵,记录每个子串是否为回文。

from typing import List

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])

力扣题目链接
题目文章讲解
题目视频讲解

  • 46
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值