leetcode 17. Letter Combinations of a Phone Number(python)|Python 主题月

1,102 阅读2分钟

本文正在参加「Python主题月」,详情查看 活动链接

描述

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

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

Example 1:

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

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Note:

0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].

解析

根据题意,该题中的 2-9 的数字模拟老旧的拨号电话机(或者现在打开你的手机拨号盘,可以对照题目看一下每个按键的内容),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 四个字母。题目要求要根据给出的 digits 字符串中的数字,返回各个数字字符代表的字母可以组成的所有可能的组合。

本题没法使用遍历,因为这循环起来一环嵌一环,不知道该写几个循环,不信你可以试试,而这种“一环套一环”的模式的题目,因为和递归的形式很像,最好的办法就是使用递归的方法,。使用字典 d 将每个数字字符对应的字母都记录下来,然后每次递归的时候,判断如果 digits 长度为 0 ,直接返回空列表;如果长度为 1 直接返回 list(d[digits]) ,否则就递归对 digits[:-1] 中的字符进行排列,等到返回结果之后,将其和此层递归的 d[digits[-1]] 中的每个结果进行逐个的组合,递归结束即可得到所有的组合列表。思路很简单, dubug 一下代码具体的细节就会明白了。

解答

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        d = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        if len(digits) == 0:
            return []
        if len(digits) == 1:
            return list(d[digits])
        tail = self.letterCombinations(digits[:-1])
        other = d[digits[-1]]
        return [s + c for s in tail for c in other]

        	      
		

运行结果

Runtime: 16 ms, faster than 77.43% of Python online submissions for Letter Combinations of a Phone Number.
Memory Usage: 13.4 MB, less than 66.04% of Python online submissions for Letter Combinations of a Phone Number.

原题链接:leetcode.com/problems/le…

您的支持是我最大的动力