leetcode(17) letter combinations of a phone number 解法:

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.

解法:

迭代法解题,即依次读取字符串中的每位数字,然后把数字对应的字母依次加到当前的所有结果中,然后进入下一次迭代。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class :
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
d = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
result = [];
if(len(digits) == 0):
return [];
di = int(digits[0]);
for j in range(len(d[di])):
result.append(d[di][j]);
i = 1;
while(i< len(digits)):
di = int(digits[i]);
tmp = [];
for x in result:
for j in d[di]:
tmp.append(x + j);
result = tmp;
i+=1;
return result;