算法 17 电话号码字母组合 - 图1

    1. # 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
    2. #
    3. # 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
    4. #
    5. #
    6. #
    7. # 示例:
    8. #
    9. # 输入:"23"
    10. # 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
    11. #
    12. #
    13. # 说明:
    14. # 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
    15. # Related Topics 深度优先搜索 递归 字符串 回溯算法
    16. # 👍 1061 👎 0
    17. # leetcode submit region begin(Prohibit modification and deletion)
    18. class Solution(object):
    19. def letterCombinations(self, digits):
    20. """
    21. :type digits: str
    22. :rtype: List[str]
    23. """
    24. phoneMap = {
    25. "2": "abc",
    26. "3": "def",
    27. "4": "ghi",
    28. "5": "jkl",
    29. "6": "mno",
    30. "7": "pqrs",
    31. "8": "tuv",
    32. "9": "wxyz",
    33. }
    34. if not digits:
    35. return []
    36. collection = []
    37. res = []
    38. def backTrace(index):
    39. if index == len(digits):
    40. res.append("".join(collection))
    41. else:
    42. digit = digits[index]
    43. if digit in phoneMap:
    44. for c in phoneMap[digit]:
    45. collection.append(c)
    46. backTrace(index + 1)
    47. collection.pop()
    48. backTrace(0)
    49. return res
    50. # leetcode submit region end(Prohibit modification and deletion)
    51. print(Solution().letterCombinations("23"))