-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_0017.py
51 lines (40 loc) · 1.32 KB
/
leetcode_0017.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 __init__(self):
self.temp = ""
self.combos: list = []
self.key_map: dict = {
"2": "abc", "3": "def",
"4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs",
"8": "tuv", "9": "wxyz"
}
def combinations(self, digits):
if not digits:
self.combos.append(self.temp)
return
words = self.key_map[digits[-1]]
for w in words:
self.temp += w
self.combinations(digits[:-1])
self.temp = self.temp[:-1]
def letterCombinations(self, digits: str) -> list[str]:
if not digits:
return self.combos
self.combinations(list(digits[::-1]))
return self.combos
s = Solution()
print(s.letterCombinations("23"))
# from itertools import product
# class Solution:
# def letterCombinations(self, digits: str) -> list[str]:
# if not digits:
# return []
# key_map = {
# "2": "abc", "3": "def",
# "4": "ghi", "5": "jkl",
# "6": "mno", "7": "pqrs",
# "8": "tuv", "9": "wxyz"
# }
# # Generate all combinations using cartesian product
# char_lists = [key_map[d] for d in digits]
# return ["".join(combo) for combo in product(*char_lists)]