您的位置:首页 > 编程语言 > Python开发

Leetcode题解(Python): 17. Letter Combinations of a Phone Number

2017-02-02 12:39 453 查看
【题目】

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


1
2
【题解】

这种题一拿到手,第一个思路就是递归,相对来说递归简单一些。

解题思路就是:将一串数字看作是第一个数字与其他数字两部分,将第一个数字对应的字母与其他数字部分的字母列表对应组合成结果。

代码:

class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
dictLetter = {0:' ', 1:'', 2:'abc', 3:'def', 4:'ghi', 5:'jkl', 6:'mno', 7:'pqrs', 8:'tuv', 9:'wxyz'}
length = len(digits)
if length == 0:
return []
intVal = int(digits[0])

result = []
arr = []
letter = dictLetter[intVal]//第一个数字部分
for l in letter:
if length > 1:
arr = self.letterCombinations(digits[1:])//其余数字部分
for a in arr:
result.append(l + a)
else:
result.append(l)

return result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
leetcode上的执行时间是52ms。

看了看discussion中的,有人用了一种记录中间值,减少重复计算的方法。

看下代码:

class Solution(object):
dictLetter = {
0 : [' '],
1 : [],
2 : ['a', 'b', 'c'],
3 : ['d', 'e', 'f'],
4 : ['g', 'h', 'i'],
5 : ['j', 'k', 'l'],
6 : ['m', 'n', 'o'],
7 : ['p', 'q', 'r', 's'],
8 : ['t', 'u', 'v'],
9 : ['w', 'x', 'y', 'z']
}
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
length = len(digits)
if length == 0:
return []

result = self.dictLetter.get(digits, [])//注意这里的digits代表string类型的第一个数字。如果输入'23',get函数返回的只dictLetter中的键为'2'的值,而不是2
if result:
return result

intVal = int(digits[0])
arr = []
letter = self.dictLetter[intVal]
for l in letter:
if length > 1:
arr = self.letterCombinations(digits[1:])
for a in arr:
result.append(l + a)
else:
result.append(l)
self.dictLetter[digits] = result//记录中间结果(以string类型作为key)

return result
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
27
28
29
30
31
32
33
34
35
36
37
38
39


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
27
28
29
30
31
32
33
34
35
36
37
38
39
leetcode上的执行时间是48ms,比上一个方法略快。

很想知道速度特别靠前的那些算法是怎么写的。如有朋友知道,望不吝赐教。

水平有限,欢迎指正~

如需转发,请注明出处,thx~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: