-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletter_combination.py
More file actions
41 lines (32 loc) · 967 Bytes
/
letter_combination.py
File metadata and controls
41 lines (32 loc) · 967 Bytes
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
class Solution:
def letterCombinations(self, digits):
if not digits:
return []
mapping = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
result = []
def backtrack(solution, idx):
if idx == len(digits):
result.append("".join(solution))
return
for letter in mapping.get(digits[idx], ""):
solution.append(letter)
backtrack(solution, idx + 1)
solution.pop()
backtrack([], 0)
return result
if __name__ == "__main__":
solution = Solution()
digits = "23"
result = solution.letterCombinations(digits)
assert result == ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
print(result)
print("Test Case 1 Passed!")