电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:
codeType
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
codeType
输入:digits = "2"
输出:["a","b","c"]
提示:
- 1 <= digits.length <= 4
- digits[i] 是范围 ['2', '9'] 的一个数字。
解法
ts
function letterCombinations(digits: string): string[] {
const num_map = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
const n = digits.length
const res: string[] = []
// 边界处理:空输入直接返回空数组
if (n === 0) return res
// 当前深度和当前拼接的字符串
const dfs = (depth: number, preStr: string) => {
// 深度等于数字长度,说明拼接完成
if (depth === n) {
res.push(preStr)
return
}
// 处理当前层:获取当前深度对应的数字 + 字符集
const curNum = digits[depth]
const curChars = num_map[curNum]
// 遍历当前字符集的所有字符,递归下一层
for (const char of curChars) {
dfs(depth + 1, preStr + char)
}
}
// 正确的初始调用:从深度0开始,初始拼接字符串为空
dfs(0, '')
return res
};