Skip to content

Commit 8949c3c

Browse files
committed
problem: 0017 letter combination of a phone number
1 parent 8e5db80 commit 8949c3c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# 0017. Letter Combinations of a Phone Number
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
5+
* Topics: Backtracking
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: string
11+
- OUTPUT: List[String]
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
- 建立數字對應的 map
18+
- Backtracking
19+
- 停止條件
20+
- len(substring) == len(inputstring)
21+
- 非停止條件
22+
- forloop
23+
- 對每個letter backtrack
24+
- Implement
25+
26+
```python
27+
class Solution:
28+
def letterCombinations(self, digits: str) -> List[str]:
29+
digit_map = {
30+
"2" : "abc",
31+
"3":"def",
32+
"4":"ghi",
33+
"5":"jkl",
34+
"6":"mno",
35+
"7":"pqrs",
36+
"8":"tuv",
37+
"9":"wxyz"
38+
}
39+
if len(digits) == 0:
40+
return []
41+
chars = list(digits)
42+
result = []
43+
def backtrack(substr, res):
44+
if len(substr) == len(digits):
45+
return result.append(substr)
46+
for i in range(len(res)):
47+
letters = list(digit_map.get(res[i]))
48+
for letter in letters:
49+
backtrack(substr+letter, res[i+1:])
50+
51+
backtrack("", chars)
52+
return result
53+
```
54+
55+
56+
### Complexity
57+
58+
- Time complexity:
59+
- Space complexity: $O(N)$
60+
- N: len(digits)

0 commit comments

Comments
 (0)