Topic:
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that number could repre Sent.
A mapping of Digit to letters (just as on the telephone buttons) is given below. Note that 1 does is not a map to any letters.
Example:
Input: "Output": ["ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
Note:
Although the above answer is in lexicographical order, your answer could are in any order you want.
This question translates into Chinese is actually relatively simple, is gives you the number, lets you output the numeral map the letter all may appear the combination situation. Letters that are mapped to the same number are not grouped together, not in alphabetical order, and each letter combination must contain one letter for all numeric mappings.
Here the use of recursion can be easily solved, just recently saw some generator related information, simply use recursive generator, more concise and convenient.
The code is as follows:
1 classSolution:2 deflettercombinations (self, digits):3 returnlist (self.recur (digits))
4 defrecur (self, x): #由于LeetCode验证代码时不会自动将生成器转化为列表, so only the generator is written outside, the main function only prints the answer 5DIC = {'2':'ABC','3':'def','4':'Ghi','5':'JKL','6':'MnO','7':'PQRS','8':'TUV','9':'WXYZ'}6 ifLen (x) = =0: #将digits为空值拿出来特别处理7 return []8 forIinchDic[x[0]]:9 ifLen (x) = = 1: #递归到digits只剩最后一个值挨个生成该值的映射Ten yieldI One Else: A forJinchSelf.lettercombinations (x[1:]): #这里返回的生成器, can be used to iterate - yieldi + j#拼接字符串, return one layer at a
Leetcode algorithm Problem python solution: 17. Letter combinations of a Phone number