Day 27 39. 组合总和 40.组合总和II 131.分割回文串

 39. 组合总和 

对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def backtracking(total,startIndex,path):
            if total > target:
                return
            if total==target:
                res.append(path[:])
                return
            for i in range(startIndex,len(candidates)):
                total+=candidates[i]
                path.append(candidates[i])
                backtracking(total,i,path)
                total-=candidates[i]
                path.pop()
        res=[]
        candidates.sort() #排序
        backtracking(0,0,[])
        return res

 40.组合总和II 

必须要去重使用过的元素不能重复选取。要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。要去重记得要对数组排序。

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        def backtrack(total,startIndex,path):
            if total>target:
                return 
            if total==target:
                res.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])
                backtrack(total,i+1,path)
                path.pop()
                total-=candidates[i]
        res=[]
        path.clear()
        res.clear()
        backtrack(0,0,[])
        return res

 131.分割回文串 

递归用来纵向遍历,for循环用来横向遍历,切割线(就是图中的红线)切割到字符串的结尾位置,说明找到了一个切割方法。

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        def backtrack(startIndex,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])
                    backtrack(i+1,path)# 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
                    path.pop()
        res=[]
        backtrack(0,[])
        return res

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值