17. 电话号码的字母组合
- 题号:17
- 来源:LeetCode
- 难度:中等
- 标签:
回溯字符串 - 语言:TypeScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
TypeScript · O(4^n) 时间 · O(n) 空间 · 更新于 2026-09-27
回溯枚举每个数字对应的字母组合
typescript
/**
* @difficulty medium
* @tags 回溯,字符串
* @time O(4^n)
* @space O(n)
* @note 回溯枚举每个数字对应的字母组合
*/
type PhoneMap = {
[key: string]: string[]
}
/**
* @17. 电话号码的字母组合
*/
function letterCombinations(digits: string): string[] {
let res: string[] = []
let phone: PhoneMap = {
'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 BackTrack = (path: string[], index: number) => {
if (path.length == digits.length) {
res.push([...path].join(''))
return
}
for (let i = 0; i < phone[digits[index]].length; i++) {
path.push(phone[digits[index]][i])
BackTrack(path, index + 1)
path.pop()
}
}
BackTrack([], 0)
return res
};源码:ts/leetcode/17. 电话号码的字母组合.ts
在 GitHub 上查看题目所在目录:lmliheng/algorithm