代码随想录day26

第一题

进行排序,然后可以在for之后做一个剪枝

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

    def operation(self,candidates,target,total,startindex):
        if total>target:
            return 
        if total==target:
            self.res.append(self.path[:])
            return
        
        for i in range(startindex,len(candidates)):
            if total+candidates[i]>target:
                break
            total+=candidates[i]
            self.path.append(candidates[i])
            self.operation(candidates,target,total,i)
            total-=candidates[i]
            self.path.pop()

use数组,用来区分树层去重,还是树枝去重。

首先需要对数组进行排序

树层去重:数值=前一个数的数值,且前一个数没用过

树枝去重:正常

class Solution(object):
    def __init__(self):
        self.path=[]
        self.res=[]

    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.use=[0]*len(candidates)
        candidates.sort()
        self.operation(candidates,target,0,0)
        return self.res

    def operation(self,candidates,target,total,startindex):
        if total>target:
            return 
        if total==target:
            self.res.append(self.path[:])
            return
        
        for i in range(startindex,len(candidates)):

           
            if i>startindex and candidates[i]==candidates[i-1] and self.use[i-1]==0:
                continue
            if total + candidates[i] > target:
                break

            total+=candidates[i]
            self.path.append(candidates[i])
            self.use[i]=True
            self.operation(candidates,target,total,i+1)
            self.use[i]=False
            total-=candidates[i]
            self.path.pop()

第三题

把startindex看作隔板,从0位置开始

截止条件,startindex到了最后

回文字符串为s [ startindex : i ],满足条件进入后续代码(if 之后执行)

class Solution(object):
    def __init__(self):
        self.path=[]
        self.res=[]

    def partition(self, s):

        self.operation(s,0)
        return self.res

    def operation(self,s,startindex):

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值