Skip to content

Commit f1faf1a

Browse files
committed
Letter Combinations of a Phone Number
1 parent 54ed345 commit f1faf1a

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# 题目
2+
3+
给定一个数字字符串,返回所有数字代表的所有字母组合结果。
4+
5+
数字到字母的映射,就像电话按钮一样。
6+
```python
7+
kvmaps = {
8+
'2': 'abc',
9+
'3': 'def',
10+
'4': 'ghi',
11+
'5': 'jkl',
12+
'6': 'mno',
13+
'7': 'pqrs',
14+
'8': 'tuv',
15+
'9': 'wxyz'
16+
}
17+
```
18+
19+
**例子:**
20+
21+
Input:Digit string "23"
22+
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
23+
24+
# 思考
25+
就是遍历所有可能组合,一个简单的方法是使用reduce函数
26+
27+
**代码:**
28+
29+
普通遍历方法:
30+
31+
```python
32+
class Solution(object):
33+
def letterCombinations(self, digits):
34+
"""
35+
:type digits: str
36+
:rtype: List[str]
37+
"""
38+
if '' == digits: return []
39+
kvmaps = {
40+
'2': 'abc',
41+
'3': 'def',
42+
'4': 'ghi',
43+
'5': 'jkl',
44+
'6': 'mno',
45+
'7': 'pqrs',
46+
'8': 'tuv',
47+
'9': 'wxyz'
48+
}
49+
ret=['']
50+
for c in digits:
51+
tmp=[]
52+
for y in ret:
53+
for x in kvmaps[c]:
54+
tmp.append(y+x)
55+
ret=tmp
56+
return ret
57+
```
58+
59+
使用reduce
60+
61+
```python
62+
class Solution(object):
63+
def letterCombinations(self, digits):
64+
"""
65+
:type digits: str
66+
:rtype: List[str]
67+
"""
68+
if '' == digits: return []
69+
kvmaps = {
70+
'2': 'abc',
71+
'3': 'def',
72+
'4': 'ghi',
73+
'5': 'jkl',
74+
'6': 'mno',
75+
'7': 'pqrs',
76+
'8': 'tuv',
77+
'9': 'wxyz'
78+
}
79+
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
80+
```

0 commit comments

Comments
 (0)