代码随想录第二十七天:39. 组合总和、40.组合总和II、131.分割回文串

文章讲述了在编程中如何使用递归方法解决组合总和问题,包括允许重复元素的情况(Solution1)和不允许重复元素的情况(Solution2),以及如何通过backtracking实现分割回文串(partition)。着重于递归策略和剪枝优化。
摘要由CSDN通过智能技术生成

39. 组合总和

这道题可以重复选取元素,所以在递归的时候就不需要从i+1开始了

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

    def backreacking(self, startindex, path, res, candidates, target):
        if sum(path) > target:  # 元素的和大于目标了就返回,等于目标了就加入res
            return
        if sum(path) == target:
            res.append(path[:])
            return
        for i in range(startindex, len(candidates)):
            if sum(path)+candidates[i] > target:  # 剪枝,若此时和已经大于target了,则没有必要进入下一层递归了
                continue
            path.append(candidates[i])
            self.backreacking(i, path, res, candidates, target)
            path.pop()

40.组合总和II

本题和上一题的区别在于,本题中candidates中元素里有重复;本题中candidates里每个元素只能用一次。同时和上一题一样结果中没有重复的。因此要去重

其实就是树枝上可以有重复元素(因为都是同一个组合里的),但是树层上不能有使用过的元素。

所以引入一个used来记录每一个元素是否被用过

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

    def backtracking(self, candidates, target, currentsum, startindex, used, path, res):
        if currentsum == target:
            res.append(path[:])
            return
        for i in range(startindex, len(candidates)):
            if i > 0 and candidates[i] == candidates[i-1] and used[i-1] == False:  # 这里的意思是,在树层上重复取过的就不要再取了,used[i-1] == False是用来说明树枝上如果取过了后面还有相同元素的话可以再取
                continue
            if candidates[i] + currentsum > target:
                break
            currentsum += candidates[i]
            path.append(candidates[i])  
            used[i] = True
            self.backtracking(candidates, target, currentsum, i+1, used, path, res)
            used[i] = False
            currentsum -= candidates[i]
            path.pop()

131.分割回文串

有点难

要想清楚其实startindex(下一轮递归遍历的起始位置)就是分割线,然后就是加一层回文串的判断

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

    def is_huiwen(self, s):
        if s != [] and s == s[::-1]:
            return True
        return False

    def backtracking(self, s, startindex, path, res):
        if startindex >= len(s):
            res.append(path[:])
            return
        for i in range(startindex, len(s)):
            if self.is_huiwen(s[startindex:i+1]):
                path.append(s[startindex:i+1])
                self.backtracking(s, i+1, path, res)
                path.pop()

题解:代码随想录代码随想录代码随想录

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值