Leetcode 17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent. The digit-to-letters mapping is given by the standard telephone number pads as follows:
2 -> "abc"
3 -> "def"
4 -> "ghi"
5 -> "jkl"
6 -> "mno"
7 -> "pqrs"
8 -> "tuv"
9 -> "wxyz"
Example:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Constraints:
2-9
?2-9
.To solve this problem, we can use a backtracking approach:
The time complexity is O(4^n * n)
, where n
is the length of the input string. This takes into account the maximum branching factor of 4 (in the worst-case scenario, digit ‘7’ or ‘9’ which maps to 4 letters) and the height of the recursion tree, which is n
.
Here’s the implementation in C++:
#include <vector>
#include <string>
class Solution {
public:
std::vector<std::string> letterCombinations(std::string digits) {
if (digits.empty()) {
return {};
}
// Mapping of digits to letters
const std::vector<std::string> digitToChar = {
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};
std::vector<std::string> result;
std::string current;
backtrack(digits, 0, current, result, digitToChar);
return result;
}
private:
void backtrack(const std::string &digits, int index, std::string ¤t, std::vector<std::string> &result, const std::vector<std::string> &digitToChar) {
if (index == digits.size()) {
result.push_back(current);
return;
}
const std::string &letters = digitToChar[digits[index] - '0'];
for (char letter : letters) {
current.push_back(letter);
backtrack(digits, index + 1, current, result, digitToChar);
current.pop_back();
}
}
};
digitToChar
that maps each digit from 2-9
to its corresponding string of letters.digits
is empty, we return an empty vector.index == digits.size()
), we add the current combination to the result.This approach ensures that every possible combination is explored efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?