forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathletter-combinations-of-a-phone-number.py
43 lines (34 loc) · 1.3 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
# Time: O(n * 4^n)
# Space: O(n)
class Solution(object):
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
if not digits:
return []
lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \
"pqrs", "tuv", "wxyz"], [""]
for digit in reversed(digits):
choices = lookup[int(digit)]
m, n = len(choices), len(result)
result += [result[i % n] for i in xrange(n, m * n)]
for i in xrange(m * n):
result[i] = choices[i / n] + result[i]
return result
# Time: O(n * 4^n)
# Space: O(n)
# Recursive Solution
class Solution2(object):
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
if not digits:
return []
lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \
"pqrs", "tuv", "wxyz"], []
self.letterCombinationsRecu(result, digits, lookup, "", 0)
return result
def letterCombinationsRecu(self, result, digits, lookup, cur, n):
if n == len(digits):
result.append(cur)
else:
for choice in lookup[int(digits[n])]:
self.letterCombinationsRecu(result, digits, lookup, cur + choice, n + 1)