17. Letter Combinations of a Phone Number #36
-
Given a string containing digits from A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 17. Letter Combinations of a Phone Number <?php
/**
* @param String $digits
* @return String[]
*/
function letterCombinations($digits) {
if (empty($digits)) {
return [];
}
$letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
$ans = [];
$curr = '';
$this->findCombinations(0, $digits, $letters, $curr, $ans);
return $ans;
}
private function findCombinations($start, $nums, $letters, &$curr, &$ans) {
if (strlen($curr) == strlen($nums)) {
$ans[] = $curr;
return;
}
for ($i = $start; $i < strlen($nums); $i++) {
$n = intval($nums[$i]);
for ($j = 0; $j < strlen($letters[$n]); $j++) {
$ch = $letters[$n][$j];
$curr .= $ch;
$this->findCombinations($i + 1, $nums, $letters, $curr, $ans);
$curr = substr($curr, 0, -1);
}
}
}
// Test the function
print_r(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
print_r(letterCombinations("")); // Output: []
print_r(letterCombinations("2")); // Output: ["a","b","c"]
?> Explanation:
This approach is efficient given the constraints and handles edge cases like empty input properly. If you have any more questions or need further modifications, let me know! |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Mapping Creation:
Create an associative array to map each digit to its corresponding letters.
Recursive Function:
Use a recursive function to build combinations. This function will take the current combination being built and the remaining digits to process.
Base Case:
When no more digits are left, add the current combination to the result list.
Recursive Case:
For each letter mapped from the current digit, append it to the current combination and recurse with the remaining digits.
Let's implement this solution in PHP: 17. Letter Combinations of a Phone Number