[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

 

posted @ 2019-05-27 18:12  夜歌乘年少  阅读(213)  评论(0编辑  收藏  举报