zoukankan      html  css  js  c++  java
  • [leetcode]20. Valid Parentheses

    参考资料:https://blog.csdn.net/puqutogether/article/details/45574903

    写一个回溯法递归快要掉了半条命。。。什么时候菜到这种地步了。。。哎

    注意在return前的那次循环后面要删除最后一个添加的字符,让循环可以继续,不会退出到主函数里。参考最后一行注释。

    Runtime: 36 ms, faster than 87.52% of Python3 online submissions forLetter Combinations of a Phone Number.
    Memory Usage: 13.2 MB, less than 41.83% of Python3 online submissions for Letter Combinations of a Phone Number.

    Submission Detail

    25 / 25 test cases passed.
    Status: 

    Accepted

    Runtime: 36 ms
    Memory Usage: 13.2 MB
    Submitted: 1 minute ago
    class Solution:
        def letterCombinations(self, digits: str) -> List[str]:
            phoneLetters = ['','', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
            represent = []
            ret = []
            lengthS = len(digits)
            # 0
            if lengthS == 0:
                return ret
            # 2-9
            for index in range(lengthS):
                indice = int(digits[index:index+1])
                represent.append(phoneLetters[indice])
            onecase =''
            self.recrusion(ret,represent,lengthS,onecase,item = 0)
            return ret
        '''
        represent: string need to recursion
        lengthS:recursion limit
        onecase:index in each recursion
        index:index in circulation
        ---
        item:index in represent
        index:index in represent[item]
        ---
        '''
        def recrusion(self,ret,represent,lengthS,onecase,item ):
            if len(onecase) == lengthS:
                ret.append(onecase)
                return
            for index in range(len(represent[item])):
                onecase += represent[item][index:index +1]
                #recursion
                self.recrusion(ret,represent,lengthS,onecase,item +1)
                onecase = onecase[:-1] #del last element which have already return(make ad ->a; a_->__)

    惯例抄一个28ms的:

    class Solution:
        def letterCombinations(self, digits: str) -> List[str]:
            if not len(digits):
                return []
            
            digit_to_chars = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
            outputs = ['']
            for d in digits:
                new_out = [o+c for c in digit_to_chars[d] for o in outputs]
                outputs = new_out
            # return sorted(outputs)
            return outputs
  • 相关阅读:
    python os.path.dirname()
    python os.path.basename()方法
    python mmap对象
    python 读取二进制数据到可变缓冲区中
    sklearn常见分类器的效果比较
    用matplotlib获取雅虎股票数据并作图
    使用 lxml 中的 xpath 高效提取文本与标签属性值
    如何用 Python 爬取需要登录的网站
    python 线程及线程池
    使用Python代码处理Excel
  • 原文地址:https://www.cnblogs.com/alfredsun/p/10932242.html
Copyright © 2011-2022 走看看