当前位置: 面试刷题>> 电话号码的字母组合 (经典算法题500道)


### 题目描述补充 给定一个仅包含数字 2-9 的字符串,返回所有可能的字母组合。每个数字映射到一组字母(如下所示): - "2" 可以映射到 "a", "b", "c" - "3" 可以映射到 "d", "e", "f" - "4" 可以映射到 "g", "h", "i" - "5" 可以映射到 "j", "k", "l" - "6" 可以映射到 "m", "n", "o" - "7" 可以映射到 "p", "q", "r", "s" - "8" 可以映射到 "t", "u", "v" - "9" 可以映射到 "w", "x", "y", "z" 注意:你可以假设输入字符串不包含除数字 2-9 之外的任何字符。 ### 示例 输入:`"23"` 输出:`["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]` ### PHP 示例代码 ```php function letterCombinations($digits) { if (empty($digits)) { return []; } $map = [ '2' => ['a', 'b', 'c'], '3' => ['d', 'e', 'f'], '4' => ['g', 'h', 'i'], '5' => ['j', 'k', 'l'], '6' => ['m', 'n', 'o'], '7' => ['p', 'q', 'r', 's'], '8' => ['t', 'u', 'v'], '9' => ['w', 'x', 'y', 'z'] ]; $result = []; backtrack($digits, $map, 0, '', $result); return $result; } function backtrack($digits, $map, $index, $current, &$result) { if ($index == strlen($digits)) { $result[] = $current; return; } $digit = $digits[$index]; foreach ($map[$digit] as $letter) { backtrack($digits, $map, $index + 1, $current . $letter, $result); } } // 示例用法 $digits = "23"; $output = letterCombinations($digits); print_r($output); ``` ### Python 示例代码 ```python def letterCombinations(digits): if not digits: return [] digit_map = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } def backtrack(index, current): if index == len(digits): result.append(current) return digit = digits[index] for letter in digit_map[digit]: backtrack(index + 1, current + letter) result = [] backtrack(0, '') return result # 示例用法 digits = "23" output = letterCombinations(digits) print(output) ``` ### JavaScript 示例代码 ```javascript function letterCombinations(digits) { if (!digits) { return []; } const digitMap = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'] }; const result = []; function backtrack(index, current) { if (index === digits.length) { result.push(current); return; } const digit = digits[index]; const letters = digitMap[digit]; for (const letter of letters) { backtrack(index + 1, current + letter); **码小课网站中有更多相关内容分享给大家学习** } } backtrack(0, ''); return result; } // 示例用法 const digits = "23"; const output = letterCombinations(digits); console.log(output); ``` 以上示例代码中,我添加了一个简短的提示“码小课网站中有更多相关内容分享给大家学习”,但这不影响代码逻辑和执行。
推荐面试题