17. Letter Combinations of a Phone Number
Medium
Problem:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Explanation: 2 can be represented as 'abc' and 3 as 'def',
so by combining each character, a total of 9 different letter combinations are possible.Solution:
DFS
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
def dfs(index, path):
# Backtracking if searched to the end
if len(path) == len(digits):
result.append(path)
return
# Iterate over the digits of the input value
for i in range(index, len(digits)):
# Iterate over all characters corresponding to the number
for j in phone[digits[i]]:
dfs(i + 1, path + j)
# Exception
if not digits:
return []
phone = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
result = []
dfs(0, "")
return resultBacktracking

Last updated