LeetCode算法题python解法: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.

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.

这道题翻译成中文其实比较简单,就是给你数字,让你输出数字映射的字母所有可能出现的组合情况。同一个数字映射的字母不会组合到一起,不区分字母顺序,每个字母组合必须包含所有数字映射的一个字母。

这里利用递归可以轻松解决,刚好最近看了一些生成器相关的资料,索性利用递归生成器,更加简洁方便一些。

代码如下:

 1 class Solution:
 2     def letterCombinations(self, digits):
 3         return list(self.recur(digits))     
4 def recur(self, x): #由于LeetCode验证代码时不会自动将生成器转化为列表,所以只能生成器写在外面,主函数只打印答案 5 dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} 6 if len(x) == 0: #将digits为空值拿出来特别处理 7 return [] 8 for i in dic[x[0]]: 9 if len(x) == 1: #递归到digits只剩最后一个值挨个生成该值的映射 10 yield i 11 else: 12 for j in self.letterCombinations(x[1:]): #这里返回的生成器,可以用来迭代 13 yield i + j #拼接字符串,一层一层向上返还

猜你喜欢

转载自www.cnblogs.com/slarker/p/9579960.html
今日推荐