LeetCode Letter Combinations of a Phone Number

LeetCode解题之Letter Combinations of a Phone Number


原题

手机按键上每一个数字都相应了多个字母,如2相应了”abc”,现给出一个数字串。要求把当中的每一个数字都转化为相应的字母中的一个,列出全部的组合情况。

注意点:

  • 对结果的排列顺序没有要求

样例:

输入: digits=”23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

解题思路

把每一个数字相应的字母都当做树的节点,例如以下图。则所求结果就是从根节点到叶节点的全部的路径,採用深度优先遍历算法。

tree

AC源代码

class Solution(object):
    digit2letters = {
        '2': "abc",
        '3': "def",
        '4': "ghi",
        '5': "jkl",
        '6': "mno",
        '7': "pqrs",
        '8': "tuv",
        '9': "wxyz",
    }

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits:
            return []
        result = []
        self.dfs(digits, "", result)
        return result

    def dfs(self, digits, current, result):
        if not digits:
            result.append(current)
            return
        for c in self.digit2letters[digits[0]]:
            self.dfs(digits[1:], current + c, result)


if __name__ == "__main__":
    assert Solution().letterCombinations("23") == ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

posted @ 2017-07-04 19:31  jhcelue  阅读(210)  评论(0编辑  收藏  举报