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”]

解题思路

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

LeetCode Letter Combinations of a Phone Number_第1张图片

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) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,排列组合)