Skip to main content

Letter Combinations of a Phone Number

Question

com

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

Example 1
None

Solution

all//Letter Combinations of a Phone Number.py


def letter_combinations(digits):
if not digits:
return []

digits_map = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
result = []
def backtrack(combination, next_digits):
if len(next_digits) == 0:
result.append(combination)
else:
for letter in digits_map[next_digits[0]]:
backtrack(combination + letter, next_digits[1:])

backtrack("", digits)
return result