[LeetCode] Challenge log 17

17. Letter Combinations of a Phone Number

It is a full permutation problem. DFS or BFS both ok.


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:

1
2
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.


Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "": return []
dic = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
res = [x for x in dic[digits[0]]]
for i in digits[1:]:
temp = []
for letter in dic[i]:
temp += [x + letter for x in res]
res = temp
return res
0%