-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathletter-combinations-of-a-phone-number.py
51 lines (42 loc) · 1.14 KB
/
letter-combinations-of-a-phone-number.py
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
40
41
42
43
44
45
46
47
48
49
50
51
class Solution:
def letterCombinations(self, digits: str) -> list[str]:
key_map: dict[str, str] = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
stack: list[str] = []
result: list[str] = []
def combinations(pos: int) -> None:
if pos == len(digits):
if stack:
result.append("".join(stack))
return
for letter in key_map[digits[pos]]:
stack.append(letter)
combinations(pos + 1)
stack.pop()
combinations(0)
return result
class TestSolution:
def setup(self):
self.sol = Solution()
def test_empty(self):
assert self.sol.letterCombinations("") == []
def test_custom1(self):
assert self.sol.letterCombinations("23") == [
"ad",
"ae",
"af",
"bd",
"be",
"bf",
"cd",
"ce",
"cf",
]