LeetCode 17. Letter Combinations of a Phone Number

String, Backtracking

Posted by baiyf on October 2, 2018

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

img

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

题意

题目给你一串2-9的数字, 需要返回所有可能的键盘字母组合,映射规则就是手机九键输入的键盘映射规则

这道题可以用递归的方法也可以不用递归的方法

  • 如果不用递归的方法,可以用Python列表生成式的来表示这种排列组合的关系

  • 也可以用递归的方法,每次递归确定一位数字,当全部都确定后递归结束

解法

  • 递归
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        dic = {2: ['a', 'b', 'c'],
               3: ['d', 'e', 'f'],
               4: ['g', 'h', 'i'],
               5: ['j', 'k', 'l'],
               6: ['m', 'n', 'o'],
               7: ['p', 'q', 'r', 's'],
               8: ['t', 'u', 'v'],
               9: ['w', 'x', 'y', 'z'],
               }
        ret_str = []
        if len(digits) == 0: return []
        # 递归出口,当递归到最后一个数的时候result拿到结果进行for循环遍历
        if len(digits) == 1:
            return dic[int(digits[0])]
        result = self.letterCombinations(digits[1:])
        for r in result:
            for j in dic[int(digits[0])]:
                ret_str.append(j + r)
        return ret_str
  • 非递归
class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
        if not digits:
            return []
        
        digit2chars = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
        
        res = [ i for i in digit2chars[digits[0]] ]
        
        for i in digits[1:]:
            res = [ m+n for m in res for n in digit2chars[i] ]
            
        return res