Problem
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.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = "" Output: []
Example 3:
Input: digits = "2" Output: ["a","b","c"]
Intuition
The problem involves generating all possible letter combinations that a given string of digits could represent. This can be approached using a depth-first search (DFS) algorithm. The idea is to explore all possible combinations by considering each digit and its associated letters.
Approach
Backtracking Function:
Implement a backtracking function (backtrack) that takes two parameters: i (the current index in the digits string) and curstr (the current string being formed).
In the base case:
If the length of the current string (curstr) is equal to the length of the digits string, append a copy of the current string to the result (res).
Otherwise, iterate over the letters associated with the current digit (digits[i]) and recursively call the backtrack function for the next index (i + 1) with the updated string (curstr + c).
After the recursive call, backtrack by removing the last added letter from the string.
Initialization:
If the digits string is not empty, call the backtrack function with the initial index i set to 0 and the initial string curstr set to an empty string.
Return Result:
Return the final result (res), which contains all possible letter combinations.
Complexity
- Time complexity:
The time complexity is O(4^N * N), where N is the length of the input digits. In the worst case, each digit can have up to 4 associated letters, and the recursion tree has a depth of N.
- Space complexity:
The space complexity is O(N) due to the recursion stack and the space required for the result (res) and the current string (curstr). The space for the recursion stack is proportional to the maximum depth of the recursion, which is N.
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
res = []
digittochar= {
'2' : 'abc',
'3' : 'def',
'4' : 'ghi',
'5' : 'jkl',
'6' : 'mno',
'7' : 'pqrs',
'8' : 'tuv',
'9' : 'wxyz'
}
def backtrack(i, curstr):
if len(curstr) == len(digits):
res.append(curstr)
return
for c in digittochar[digits[i]]:
backtrack(i + 1, curstr + c)
if digits:
backtrack(0, '')
return res