-
Notifications
You must be signed in to change notification settings - Fork 0
/
0017-letter-combinations-of-a-phone-number.py
59 lines (53 loc) · 1.98 KB
/
0017-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
52
53
54
55
56
57
58
59
class Solution:
def letterCombinations(self, digits):
return self.letterCombinationsRecursive(digits)
# O(n*4^n) time and O(n*4^n) space
def letterCombinationsRecursive(self, digits):
def letterCombinationsHelper(digits, associations, start, prefix, combinations):
if start == len(digits):
if len(prefix) != 0:
combinations.append("".join(prefix[:]))
return
for button in associations[digits[start]]:
prefix.append(button)
letterCombinationsHelper(digits, associations, start + 1, prefix, combinations)
prefix.pop()
associations = {
"0": ["0"],
"1": ["1"],
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"],
}
start = 0
prefix = []
combinations = []
letterCombinationsHelper(digits, associations, start, prefix, combinations)
return combinations
# O(n*4^n) time and O(n*4^n) space
def letterCombinationsIterative(self, digits):
combinations = [""] if len(digits) > 0 else []
associations = {
"0": ["0"],
"1": ["1"],
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"],
}
for digit in digits:
current = []
for button in associations[digit]:
for combination in combinations:
current.append(combination + button)
combinations = current
return combinations