Skip to content

Commit 1a83bdb

Browse files
authored
Create 17_Letter_Combinations_of_a_Phone_Number.md
1 parent 9f21369 commit 1a83bdb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
## 17. Letter Combinations of a Phone Number
2+
3+
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
4+
5+
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
6+
7+
8+
Example 1:
9+
10+
Input: digits = "23"
11+
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
12+
Example 2:
13+
14+
Input: digits = ""
15+
Output: []
16+
Example 3:
17+
18+
Input: digits = "2"
19+
Output: ["a","b","c"]
20+
21+
22+
Constraints:
23+
24+
0 <= digits.length <= 4
25+
digits[i] is a digit in the range ['2', '9'].
26+
27+
28+
29+
```python
30+
def letterCombinations(self, digits: str) -> List[str]:
31+
result = []
32+
if digits == "":
33+
return result
34+
dic = {
35+
'2': 'abc',
36+
'3': 'def',
37+
'4': 'ghi',
38+
'5': 'jkl',
39+
'6': 'mno',
40+
'7': 'pqrs',
41+
'8': 'tuv',
42+
'9': 'wxyz'
43+
}
44+
45+
def combine(build, index):
46+
47+
if index == len(digits):
48+
result.append(build)
49+
return
50+
51+
chars = dic[digits[index]]
52+
for c in chars:
53+
combine(build+c, index+1)
54+
55+
combine("", 0)
56+
return result
57+
```
58+
59+
60+
```
61+
Runtime: 32 ms, faster than 51.40% of Python3 online submissions for Letter Combinations of a Phone Number.
62+
Memory Usage: 14.3 MB, less than 100.00% of Python3 online submissions for Letter Combinations of a Phone Number.
63+
```

0 commit comments

Comments
 (0)