Skip to content

Commit 3b67b32

Browse files
committed
52. Letter Combinations of a Phone Number
1 parent 3d87013 commit 3b67b32

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
2+
3+
# A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
4+
5+
6+
7+
8+
# Example 1:
9+
10+
# Input: digits = "23"
11+
# Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
12+
# Example 2:
13+
14+
# Input: digits = ""
15+
# Output: []
16+
# Example 3:
17+
18+
# Input: digits = "2"
19+
# Output: ["a","b","c"]
20+
21+
22+
# Constraints:
23+
24+
# 0 <= digits.length <= 4
25+
# digits[i] is a digit in the range ['2', '9'].
26+
27+
from typing import List
28+
29+
class Solution:
30+
def letterCombinations(self, digits: str) -> List[str]:
31+
if not digits:
32+
return []
33+
34+
phone_map = {
35+
"2": "abc",
36+
"3": "def",
37+
"4": "ghi",
38+
"5": "jkl",
39+
"6": "mno",
40+
"7": "pqrs",
41+
"8": "tuv",
42+
"9": "wxyz"
43+
}
44+
result = []
45+
46+
# for "23"
47+
# index=0 -> 2 -> path=["a"] + backtrack for next index
48+
# then path=["b"] + backtrack for next index
49+
50+
def backtrack(index, path):
51+
# if index == len(digits) need to stop
52+
if index == len(digits):
53+
result.append("".join(path))
54+
return
55+
56+
possible_letters = phone_map[digits[index]]
57+
for letter in possible_letters:
58+
# add letter to path
59+
# and call backtrack next index
60+
path.append(letter)
61+
backtrack(index+1, path)
62+
# delete last letter from path
63+
path.pop()
64+
65+
# start from 0 index of digits
66+
# and nothing in path
67+
backtrack(0, [])
68+
return result
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import unittest
2+
from solution import Solution
3+
4+
5+
class TestSolution(unittest.TestCase):
6+
def test_1(self):
7+
digits = "23"
8+
expected = ["ad","ae","af","bd","be","bf","cd","ce","cf"]
9+
self.assertCountEqual(Solution().letterCombinations(digits), expected)
10+
11+
def test_2(self):
12+
digits = ""
13+
expected = []
14+
self.assertCountEqual(Solution().letterCombinations(digits), expected)
15+
16+
def test_3(self):
17+
digits = "2"
18+
expected = ["a","b","c"]
19+
self.assertCountEqual(Solution().letterCombinations(digits), expected)

0 commit comments

Comments
 (0)