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

1.39. 组合总和

题目链接:39. 组合总和
文档讲解: 代码随想录

这道题和昨天做的组合之和由两个区别:被选的元素没有数量限制,同时被选的元素可以无限重复,只对总和进行限制。那么终止条件可以定为,和大于等于目标。单层逻辑,和组合之和一样的思路,只是在递归中不用 i + 1。最后是输入参数:整数数组、目标和、startindex(因为在一个数组里选择,避免重复)、和(记录遍历元素之和)、结果列表、路径列表。

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        self.backtracking(candidates, target, 0, 0, res, [])
        return res

    def backtracking(self, candidates, target, startindex, summ, res, path):
        #终止条件
        if summ > target:
            return
        if summ == target:
            res.append(path[:])
            return
        
        for i in range(startindex, len(candidates)):
            path.append(candidates[i])
            summ += candidates[i]
            self.backtracking(candidates, target, i, summ, res, path)
            summ -= candidates[i]
            path.pop()

关于剪枝:如果加上本层递归的元素值,和已经大于目标值的情况,仍然会在进入下一层递归的时候才能判断和大于目标值,从而 return。因此,可以在本层判断是否加上本层元素值大于目标值来进行剪枝操作。一个非常重要的点就是,在进行递归前,需要将 candidates 数组进行排序。

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        self.backtracking(candidates, target, 0, 0, res, [])
        return res

    def backtracking(self, candidates, target, startindex, summ, res, path):
        #终止条件
        if summ == target:
            res.append(path[:])
            return
        
        for i in range(startindex, len(candidates)):
            #剪枝
            if summ + candidates[i] > target:
                break

            path.append(candidates[i])
            summ += candidates[i]
            self.backtracking(candidates, target, i, summ, res, path)
            summ -= candidates[i]
            path.pop()

递归的第二个版本:与上一个版本的区别在于,不定义一个记录和的变量,使用 target 减去元素值,通过判断是否为0来终止递归。需要注意的是,终止条件包含两种情况:目标值为0,以及值小于0。

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        self.backtracking(candidates, target, 0, res, [])
        return res
        
    def backtracking(self, candidates, target, startindex, res, path):
        if target == 0:
            res.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, res, path)
            path.pop()

剪枝版本:就是在进行下一层递归前判断是否减去本层值小于0。依然是需要排序。

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        self.backtracking(candidates, target, 0, res, [])
        return res
        
    def backtracking(self, candidates, target, startindex, res, path):
        if target == 0:
            res.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, res, path)
            path.pop()

2.40.组合总和II

题目链接:40.组合总和II
文档讲解: 代码随想录

我的思路:和上一题不同的是,每个数字在每个组合中只能使用一次,只能使用一次的两个意思,递归时开始指针变为 i + 1,同时需要考虑到整型数组里有重复元素。那在开始前先进行排序,使用双指针的方法,用 pre 指针记住当前遍历的前一个元素,若相同直接 break 该层循环,从而达到去重的效果。没做出来,发现我理解错题目意思了,元素在同一个组合内是可以重复的,怎么重复都没事,但两个组合不能相同。这是我昨天的思路,我今天想到,这个是数组,不用 pre 指针,它可以通过 i - 1的下标来取前一个元素。这种思路会将例如 [1,1,6] 的组会去掉。

题解:整型数组里有重复元素,例如[10,1,2,7,4,1,6],目标值为8,第一个1和7组合,7和第二个1组合,这两个组合一样,需要去重。但第一个1,6,第二个1组合是允许的。因此,要去重的是同一树层上的相同元素,同一树枝上是一个组合里的元素,是可以重复的,因此不用去重。

在这里插入图片描述

class Solution(object):  
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        res = []
        self.backtracking(candidates, target, res, [], 0)
        return res
       
    def backtracking(self, candidates, target, res, path, startindex):
        #终止条件
        if target == 0:
            res.append(path[:])
            return #结束函数
        
        for i in range(startindex, len(candidates)):
            #去重
            if i > startindex and candidates[i] == candidates[i - 1]:
                continue#结果该层for循环
            
            if target - candidates[i] < 0:
                break#结束for循环
            
            path.append(candidates[i])
            self.backtracking(candidates, target - candidates[i], res, path, i + 1)
            path.pop()
class Solution(object):  
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
       #使用used数组
        candidates.sort()
        uesd = [False] * len(candidates)
        res = []
        self.backtracking(candidates, target, uesd, res, [], 0)
        return res

    def backtracking(self, candidates, target, used, res, path, startindex):
        if target == 0:
            res.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 target - candidates[i] < 0:
                break
            path.append(candidates[i])
            used[i] = True
            self.backtracking(candidates, target - candidates[i], used, res, path, i + 1)
            path.pop()
            used[i] = False

3.131.分割回文串

题目链接:131.分割回文串
文档讲解: 代码随想录

这道题有如下几个难点:

(1)为什么切割问题可以抽象为组合问题
假设对于字符串abcde,切割问题思路是,先切割 a,再在bcde中切割第二段,切割 b 后,再切割第三段,这与组合的选取思路是类似的,因此可以抽象为组合问题

(2)如何模拟切割线
使用startindex表示切割线

(3)切割问题中递归如何终止
当遍历到字符串末尾时,则说明已经找到一种切割方法,每个叶子节点就是一种切割结果。因为本题中,切割出来的不是回文子串是不会向下递归的

(4)在递归循环中如何截取子串
从 startindex到 i 的范围就是切割出来的子串

(5)如何判断回文
使用双指针法,一个指针从前往后,一个指针从后往前,如果前后指针所指向的元素是相等的,则为回文子串

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.backtracking(s, 0, res, [])
        return res

    def backtracking(self, s, startindex, res, path):
        #终止条件
        if startindex == len(s):
            res.append(path[:])
            return
        
        for i in range(startindex, len(s)):
            #判断是否为回文
            if self.ishuiwen(s, startindex, i):
                #是回文
                path.append(s[startindex:i + 1]) #左闭右开
                self.backtracking(s, i + 1, res, path)
                path.pop()

    def ishuiwen(self, s, left, right):
        #左闭右闭
        while left <= right:
            if s[left] != s[right]:
                return False
            left += 1
            right -= 1
        return True

这道题的优化都是在优化判断是否为回文子串上。

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.backtracking(s, 0, res, [])
        return res
        
    def backtracking(self, s, startindex, res, path):
        if startindex == len(s):
            res.append(path[:])
            return
        
        for i in range(startindex, len(s)):
            #是否为回文
            if s[startindex:i + 1] == s[startindex:i + 1][::-1]:
                path.append(s[startindex:i + 1])
                self.backtracking(s, i + 1, res, path)
                path.pop() 

具体来说,给定一个字符串 s,长度为 n,成为回文串的充分必要条件是 s[0] == s[n -1] 且 s[1:n - 1] 也是回文串,因此可以在回溯算法前,计算出 s 中所有子串是否为回文串,然后递归的时候直接查询就可以了。

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        
        hwjuzhen = [[False] * len(s) for i in range(len(s))]
        self.huiwencom(s, hwjuzhen)
        res = []
        self.backtracking(s, 0, res, [], hwjuzhen)
        return res

    def backtracking(self, s, startindex, res, path, hwjuzhen):
        if startindex == len(s):
            res.append(path[:])
            return 
        for i in range(startindex, len(s)):
            if hwjuzhen[startindex][i]:
                path.append(s[startindex:i + 1])
                self.backtracking(s, i + 1, res, path, hwjuzhen)
                path.pop()
        
    def huiwencom(self, s, hwjuzhen):
        for i in range(len(s) - 1, -1, -1):
            for j in range(i, len(s)):
                if i == j:
                    #单个字母必是回文串
                    hwjuzhen[i][j] = True
                elif j - i == 1:
                    #两个字母判断是否相同
                    hwjuzhen[i][j] = (s[i] == s[j])
                else:
                    hwjuzhen[i][j] = (s[i] == s[j] and hwjuzhen[i + 1][j - 1])

还可以使用python内置的 all 函数来判断是否回文。

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.backtracking(s, 0, res, [])
        return res

    def backtracking(self, s, startindex, res, path):
        if startindex == len(s):
            res.append(path[:])
            return
        for i in range(startindex, len(s)):
            sub = s[startindex:i + 1]
            if self.ishuiwen(sub):
                path.append(s[startindex: i + 1])
                self.backtracking(s,i + 1, res, path)
                path.pop()
    
    def ishuiwen(self, s):
        return all(s[i] == s[len(s) - 1 -i] for i in range(len(s) // 2))
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第二十二天的算法训练主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,使得子数组的和大于等于给定的目标值。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口中的元素的和满足题目要求。具体实现的代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float('inf') total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float('inf') else 0 ``` 以上就是第二十二天的算法训练的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值