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

  39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        results=[]
        self.backward(candidates,target,0,results,[],0)
        return results
        #注意index从0开始
    def backward(self,candidates,target,startindex,results,path,total):
        if total>target:
            return
        if total==target:
            results.append(path[:])
            return
            #注意return
        for i in range(startindex,len(candidates)):
            path.append(candidates[i])
            total+=candidates[i]
            self.backward(candidates,target,i,results,path,total)
            total-=candidates[i]
            path.pop()

40.组合总和II 

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。


class Solution:

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:

        results=[]

        candidates.sort()

        self.backward(candidates,target,0,results,[],0)

        return results

        #注意index从0开始

    def backward(self,candidates,target,startindex,results,path,total):

        if total==target:

            results.append(path[:])

            return

            #注意return

        for i in range(startindex,len(candidates)):

            if i>startindex and candidates[i]==candidates[i-1]:

                continue

            if total+candidates[i]>target:

                break

            path.append(candidates[i])

            total+=candidates[i]

            self.backward(candidates,target,i+1,results,path,total)

            total-=candidates[i]

            path.pop()

131.分割回文串

给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

子字符串 是字符串中连续的 非空 字符序列

回文 串是向前和向后读都相同的字符串。


class Solution:
    def partition(self, s: str) -> List[List[str]]:
        results=[]
        self.backward(s,results,0,[])
        return results

    def backward(self,s,results,startindex,path):
        if startindex==len(s):
            results.append(path[:])
            #path副本
            return
        for i in range(startindex,len(s)):
            if self.huuh(s,startindex,i)==True:
                path.append(s[startindex:i+1])
                self.backward(s,results,i+1,path)
                path.pop()

    def huuh(self,s,start,end):
        while start<end:
            if s[start]!=s[end]:
                return False
            start+=1
            end-=1
        return True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值