代码随想录算法训练营第二十三天 | 39. 组合总和、40.组合总和II、131.分割回文串

一、39. 组合总和

题目链接:39. 组合总和 - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)——39. 组合总和
视频讲解:带你学透回溯算法-组合总和(对应「leetcode」力扣题目:39.组合总和)| 回溯法精讲!_哔哩哔哩_bilibili

Note:第二个元素的分支不带第一个元素

"""
回溯算法,未剪枝
"""
class Solution:
    # 1. 确定递归函数的参数和返回值
    # sum,统计组合之和
    def backtracking(self, path, result, candidates, target, sum, startindex):
        # 2. 确定递归终止条件,总和大于目标值
        if sum > target:
            return
        # 总和等于目标值
        if sum == target:
            result.append(path[:])
            return
        
        # 3. 确定单层递归逻辑
        for i in range(startindex, len(candidates)):
            sum += candidates[i]                                            # 统计总和
            path.append(candidates[i])
            self.backtracking(path, result, candidates, target, sum, i)     # 因为可以重复选取元素,startindex不用i+1了
            sum -= candidates[i]                                            # 回溯
            path.pop()                                                      # 回溯


    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        self.backtracking([], result, candidates, target, 0, 0)
        return result

剪枝:先排序,只要有一个分支sum大于target,则没有必要继续遍历,剪枝。

"""
回溯算法,剪枝操作
"""
class Solution:
    # 1. 确定递归函数的参数和返回值
    # sum,统计组合之和
    def backtracking(self, path, result, candidates, target, sum, startindex):
        # 2. 确定递归终止条件,总和大于目标值
        if sum > target:
            return
        # 总和等于目标值
        if sum == target:
            result.append(path[:])
            return
        
        # 3. 确定单层递归逻辑
        for i in range(startindex, len(candidates)):
            # 如果sum+当前值比target大,则没有必要继续遍历,剪枝
            if sum + candidates[i] > target:
                break
            sum += candidates[i]                                            # 统计总和
            path.append(candidates[i])
            self.backtracking(path, result, candidates, target, sum, i)     # 因为可以重复选取元素,startindex不用i+1了
            sum -= candidates[i]                                            # 回溯
            path.pop()                                                      # 回溯


    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()                                                   # 剪枝操作需要先对candidates排序
        self.backtracking([], result, candidates, target, 0, 0)
        return result

二、40.组合总和II

题目链接:40. 组合总和 II - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)——40.组合总和II
视频讲解:回溯算法中的去重,树层去重树枝去重,你弄清楚了没?| LeetCode:40.组合总和II_哔哩哔哩_bilibili

树层去重:同一树层不可以取相同元素,但树枝上可以取,因为它们属于不同位置。先排序,如果遇到相同元素,第二个不再取。

class Solution:
    # 1. 确定递归函数的参数和返回值
    # used,用来记录哪些元素用过
    def backtracking(self, candidates, target, sum, path, result, startindex, used):
        # 2. 确定递归终止条件
        if sum > target:
            return
        if sum == target:
            result.append(path[:])
            return

        
        # 3. 确定单层递归逻辑
        for i in range(startindex, len(candidates)):
            # 去重,如果当前元素与前一个元素相同,且i-1在当前分支中没被使用即used[i - 1] == False,则continue
            if i > startindex and candidates[i] == candidates[i - 1] and used[i - 1] == False:
                continue
            
            path.append(candidates[i])
            sum += candidates[i]
            used[i] = True                                                             # 当前元素用过了,赋值True
            self.backtracking(candidates, target, sum, path, result, i + 1, used)      # 递归,startindex不可以重复选取元素,所以i+1
            path.pop()                                                                 # 回溯
            sum -= candidates[i]                                                       # 回溯
            used[i] = False                                                            # 回溯



    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        used = [False] * len(candidates)                                               # 初始化used
        result = []
        candidates.sort()                                                              # 排序
        self.backtracking(candidates, target, 0, [], result, 0, used)
        return result

Note:一般startindex初始都为0,77. 组合 - 力扣(LeetCode)216. 组合总和 III - 力扣(LeetCode)两道题目需要从1开始遍历,因此startindex设为1。

三、131.分割回文串

题目链接:131. 分割回文串 - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)——131.分割回文串
视频讲解:带你学透回溯算法-分割回文串(对应力扣题目:131.分割回文串)| 回溯法精讲!_哔哩哔哩_bilibili

抽象成树形结构:

class Solution:
    # 1. 确定递归函数的参数和返回值
    # path,一维数组,用来存放切割方案
    def backtracking(self, s, path, result, startindex):
        # 2. 确定递归终止条件,切割到字符串最后表示终止,startindex就是切割线
        if startindex == len(s):
            result.append(path[:])
            return

        # 3. 确定单层递归逻辑
        for i in range(startindex, len(s)):
            # 判断切割字串是否是回文串,切片边界条件是所闭右开,所以要i+1
            if s[startindex:i + 1] == s[startindex:i + 1][::-1]:
                path.append(s[startindex:i + 1])
                self.backtracking(s, path, result, i + 1)

                # 回溯
                path.pop()

        
    def partition(self, s: str) -> List[List[str]]:
        result = []
        self.backtracking(s, [], result, 0)
        return result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值