-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy path0017-Letter-Combinations-of-a-Phone-Number.py
67 lines (50 loc) · 2.04 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
60
61
62
63
64
65
66
67
'''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
'''
# Method1 using Backtracking
class Solution:
def backtrack(self, res, m, digits, combination, index):
if index > len(digits):
return
if len(combination) == len(digits):
res.append(combination)
return
cur_digit = digits[index]
cur_string = m[cur_digit]
for s in cur_string:
self.backtrack(res, m, digits, combination + s, index + 1)
def letterCombinations(self, digits: str) -> List[str]:
res = []
if not digits:
return res
m = {'2' : 'abc', '3' : 'def', '4' : 'ghi', '5' : 'jkl', '6' : 'mno', '7' : 'pqrs', '8' : 'tuv', '9' : 'wxyz'}
self.backtrack(res, m, digits, '', 0)
return res
# Method 2 using Backtracking but shorthand
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
res = []
if not digits:
return res
mapping = {'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']}
def backtrack(combination, next_digits):
if not next_digits:
res.append(combination)
else:
for letter in mapping[next_digits[0]]:
backtrack(combination + letter, next_digits[1:])
backtrack("", digits)
return res