zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 93

    Generalized Abbreviation

    要点:不算难题,注意这类递归的题要按super set的方式(选or不选),而不是combination。比较容易理解。

    • 这题的限制条件是abbreviation的部分要连成一片。
      • 如果是subset方法,因为是从左向右,所以记录左边的count,然后要不reset,然后填入字母,或者继续count+=1。
      • 如果是combination的方法,每选k(k>=0)个进入下一层。注意要在本层把下一个字母加上,下层要从该字母之后开始,这样不会出现连续数字的情况
    • 这里涉及一个何时结束的问题。这类题的要点都是在下一个位置更新,因为最后是结束在index==n的位置
    • 注意res用+=创建新object比较好,不用考虑backtrack的问题。反正最后也要copy之后添加到solutions里

    https://repl.it/CbpH/1

    # Write a function to generate the generalized abbreviations of a word.
    
    # Example:
    # Given word = "word", return the following list (order does not matter):
    # ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
    
    
    class Solution(object):
        def generateAbbreviations(self, word):
            """
            :type word: str
            :rtype: List[str]
            """
            def helper(word, res, solutions):
                if not word:
                    solutions.append(res)
                    return
                
                helper(word[1:], res+word[0], solutions)
                
                for i in xrange(len(word)):
                    helper(word[i+2:], res+str(i+1)+word[i+1:i+2], solutions)
            
            solutions = []
            helper(word, "", solutions)
            return solutions
    
    sol = Solution()
    assert sol.generateAbbreviations('word')==["word","wor1","wo1d","wo2","w1rd","w1r1","w2d","w3","1ord","1or1","1o1d","1o2","2rd","2r1","3d","4"]
    
    
  • 相关阅读:
    MySQL官方文档-二级索引覆盖主键索引
    windows server 2008/win7 远程控制
    博客园美化日记
    MarkDown 中使用 LaTeX 数学式
    DOS命令和bat脚本
    数据链路层
    网络安全
    运输层安全协议SSL
    DNS/域名
    停止等待协议
  • 原文地址:https://www.cnblogs.com/absolute/p/5815843.html
Copyright © 2011-2022 走看看