LeetCode Letter Combinations of a Phone Number

来源:互联网 发布:通达信软件使用教程 编辑:程序博客网 时间:2024/05/22 03:37

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

0 0
原创粉丝点击