Leetcode - No.17 Letter Combinat

作者: KidneyBro | 来源:发表于2018-10-08 00:29 被阅读3次

    Description

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
    A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

    字典穷举匹配问题,本解答使用暴力穷举。

    1(   )  2(abc)  3(def)
    4(ghi)  5(jkl)  6(mno)
    7(pqrs) 8(tuv)  9(wxyz)
    *( + )  0(   )  #(shift)
    E.g 1:
    Input: "23"
    Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
    
    import copy
    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            res = []
            if not digits:
                return res
            digit_mapping = {'2':"abc", '3':"def", '4':"ghi", '5':"jkl", '6':"mno", '7':"pqrs", '8':"tuv", '9':"wxyz"}
            if len(digits) == 1:
                return list(digit_mapping[digits])
            if "1" in digits:
                return []
            length = len(digits)
            init_sub_str = digit_mapping[digits[0]]
            for init_sub_char in init_sub_str:
                self.combine(init_sub_char, digit_mapping, 1, length, digits, res)
            
            return res
    

    相关文章

      网友评论

        本文标题:Leetcode - No.17 Letter Combinat

        本文链接:https://www.haomeiwen.com/subject/yutdaftx.html