手机按键上每个数字都对应了多个字母,如2对应了”abc”,现给出一个数字串,要求把其中的每个数字都转化为对应的字母中的一个,列出所有的组合情况。
注意点:
例子:
输入: digits=”23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]
把每个数字对应的字母都当做树的节点,如下图,则所求结果就是从根节点到叶节点的所有的路径,采用深度优先遍历算法。
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来获得相关源码。
LeetCode Letter Combinations of a Phone Number
原文:http://blog.csdn.net/u013291394/article/details/50363733