题目

Given a digit string, 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.

Input:Digit string “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.

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def letterCombinations(self, digits):
if digits == "":
return []
d = {
"1": "",
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
"0": "",
}
r = [""]
for i in range(0, len(digits)):
l = len(r)
for z in range(0, l):
if len(r[0]) == i:
t = r[0]
r.remove(r[0])
for j in d[digits[i]]:
r.append(t+j)
return r