首页 > 其他分享 >代码训练营 Day23| 39. 组合总和 |40.组合总和II |131.分割回文串

代码训练营 Day23| 39. 组合总和 |40.组合总和II |131.分割回文串

时间:2024-09-05 12:23:11浏览次数:7  
标签:39 target 组合 self startindex result path backtracking 总和

39. 组合总和

1. 组合没有数量要求

2. 元素可无限重复选取

class Solution(object):
    def backtracking(self,cadinates,target,sum_,startindex,path,result):
        # recursion stop condition
        if sum_ > target:
            # we can't find any answer set
            return 
        if sum_ == target:
            # collect the answer set
            result.append(path[:])
            return
        
        # each level recursion logic
        for i in range(startindex,len(cadinates)):
            # add number to our array
            sum_ += cadinates[i]
            path.append(cadinates[i])
            # recursion
            self.backtracking(cadinates,target,sum_,i,path,result)
            # backtracking
            sum_ -= cadinates[i]
            path.pop()

    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        # sort the cadinates array
        candidates.sort()
        result = [] # collect our answer set

        self.backtracking(candidates,target,0,0,[],result)

        return result
        

40.组合总和II 

0. nums集合要排序,要把相同的元素相邻再一起

1. 需要去重,不能出现重复的组合

2. 树层去重,树枝去重

   1. 需要一个变量告诉我们,那个元素我们使用过

      1. 如果该元素使用过赋值为1,如果没用过就是0

3. 树层去重

   1. 前面取过的元素,后面就不能再取了

4. 使用used去重的逻辑:遍历到当前节点时,是否还在同一个树枝上,如果不是,则去掉。

class Solution(object):
    def backtracking(self,canidates,target,total,startindex,path,result,used):
        # recursion end condition
        if total > target:
            # we can't find any answer set
            return
        if total == target:
            result.append(path[:])
            return
        
        # each level recursion logic
        for i in range(startindex,len(canidates)):
            # 对于相同的数字,只选择第一个未被使用的数字,跳过其他相同数字
            if i > startindex and canidates[i] == canidates[i-1] and used[i-1] == 0:
                # this mean's we still used same node before, we used just continue to next one
                continue
            # add element into our array
            total += canidates[i]
            path.append(canidates[i])
            # update our used boolean value
            used[i] = True
            # recursion
            self.backtracking(canidates,target,total,i+1,path,result,used)
            # backtracking
            path.pop()
            total -= canidates[i]
            used[i] = False

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

131.分割回文串 

0. 回文串: 是指一个字符串从左往右读和从右往左读是一样的

1. 如果选择了a那就在后面剩余的字母选择

    选择了b的话选择b后面的字母,以此类推

2. 分割:

    1. 选完第一个字母之后就在后面分割

    2. 选择分割的那个区间形成了一个子串

 3. startindex就是切割线

    1. 一开始切割的a

    2. 下一层startindex就是从i+1开始,也就是切割了第二个

 4. [startindex,i] 这个区间就是我们切割的子串

    1. i是一直++的,startindex一开始是固定的值,startindex是一个切割线

        i就向后移动,每向后移动一位,就代表一个子串,再向后移动就代表一个子串

class Solution(object):
    def isPalindrome(self,s,start,end):
        """ 
            check if the string is palindrome
            return True,  if it's palindrome
            return False, if it's not palindrome
        """
        # define two pointer
        left = start
        right = end

        while left <= right:
            if s[left] != s[right]:
                # since string start and end are same, it is palindrome
                return False
            # move pointer
            left += 1
            right -= 1
        
        return True
    
    def backtracking(self,s,startindex,path,result):
        # recursion end condition
        if startindex >= len(s):
            # collect the answer
            result.append(path[:])
            return
        
        # recrusion logic
        for i in range(startindex,len(s)):
            # check if it's palindrome
            if(self.isPalindrome(s,startindex,i)):
                # it is palindrome
                path.append(s[startindex:i+1])
                # recursion
                self.backtracking(s,i+1,path,result)
                # backtracking
                path.pop()
            else:
                # it's not palindrome, continue do not go to recursion
                continue
            
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        result = []
        self.backtracking(s,0,[],result)

        return result

标签:39,target,组合,self,startindex,result,path,backtracking,总和
From: https://blog.csdn.net/NeighborKing/article/details/141927728

相关文章

  • 【转载】P1399 [NOI2013] 快餐店 题解
    作者%%%%%%NightTide%%%%%%题目大意求一棵基环树的重心。即一个点,使得树上到其距离最长的点到其的距离最短。注意,这个点不一定是一个节点,可以在树上的任意位置。输出树上到其距离最长的点到其的距离。或者说求基环树最短的直径?(大雾解题思路显然,这颗基环树的直径只有两......
  • 239java jsp SSM Springboot超市便利店信息管理系统超市供应商信息商品采购收银员工管
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • MySQL常用窗口函数总和
    在MySQL中,窗口函数是一类用于在查询结果集中计算值的函数,允许用户根据数据行进行聚合或排序操作,同时保留行的详细信息。窗口函数在分析数据时非常有用,因为它们允许您在不缩小结果集的情况下对数据进行复杂的计算。常见的窗口函数包括:ROW_NUMBER()RANK()DENSE_RANK()NTILE(......
  • 139. 单词拆分(leetcode)
    https://leetcode.cn/problems/word-break/description/classSolution{publicbooleanwordBreak(Strings,List<String>wordDict){//思路较为巧妙,和传统背包定义不同//f[i]表示长度为i的字符串能否被wordDict里的单词凑成//状态转义方......
  • fatal: unable to access 'https://aomedia.googlesource.com/aom.git/': Failed to c
     低版本的Mac安装PHP就是受罪brewinstallshivammathur/php/[email protected]:YouareusingmacOS11.We(andApple)donotprovidesupportforthisoldversion.Itisexpectedbehaviourthatsomeformulaewillfailtobuildinthisoldversion.Itisexpec......
  • 力扣刷题--1837.K进制表示下的各位数字总和【简单】
    题目描述......
  • Error: xz: undefined method `deny_network_access!' for Formulary::FormulaNamespa
      ==>Fetchingxz==>Downloadinghttps://raw.githubusercontent.com/Homebrew/homebrew-core/c7f385112a4c2b9eed76b346d11d333fa8954a89/Formula/x/xz.rbAlreadydownloaded:/Users/wboll/Library/Caches/Homebrew/downloads/049af374432798d3b924a0d36bdcd6......
  • mac 上golang编译 安卓系统的so 错误 'android/log.h' file not found
    lib.gopackagemainimport"C"//exportSpeedTestfuncSpeedTest(config*C.char){ configContent:=C.GoString(config) run(configContent)}funcmain(){}需要安装NDK,用Androidstudio安装,在SDKManeger的SDKTool里选择安装NDK(sidebyside),成功后一般在......
  • 升级程序后报错 :Parse error: syntax error, unexpected ':', expecting
    当您看到类似“Parseerror:syntaxerror,unexpected':',expecting...”这样的错误时,这通常是因为PHP代码中存在语法错误。具体来说,这通常是因为某个语法特性在当前PHP版本中不被支持。常见原因PHP版本不兼容:新代码可能使用了较新版本的PHP语法特性,而当前服务器上......
  • 异步任务组合神器CompletableFuture
    使用Demoimportjava.util.concurrent.*;importjava.util.concurrent.atomic.AtomicInteger;publicclassCompletableFutureDemo{privatestaticAtomicIntegercount=newAtomicInteger(2);publicstaticvoidmain(String[]args)throwsInterrupte......