Skip to content

Commit cb83fd1

Browse files
committed
17. 电话号码的字母组合
1 parent 7d7801d commit cb83fd1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
|13|[罗马数字转整数](https://leetcode.cn/problems/roman-to-integer/)|[JavaScript](./algorithms/roman-to-integer.js)|Easy|
2121
|14|[最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)|[JavaScript](./algorithms/longest-common-prefix.js)|Easy|
2222
|15|[三数之和](https://leetcode.cn/problems/3sum/)|[JavaScript](./algorithms/3sum.js)|Medium|
23+
|17|[电话号码的字母组合](https://leetcode.cn/problems/letter-combinations-of-a-phone-number/)|[JavaScript](./algorithms/letter-combinations-of-a-phone-number.js)|Medium|
2324
|18|[四数之和](https://leetcode.cn/problems/4sum/)|[JavaScript](./algorithms/4sum.js)|Medium|
2425
|19|[删除链表的倒数第 N 个结点](https://leetcode.cn/problems/remove-nth-node-from-end-of-list/)|[JavaScript](./algorithms/remove-nth-node-from-end-of-list.js)|Medium|
2526
|20|[有效的括号](https://leetcode.cn/problems/valid-parentheses/)|[JavaScript](./algorithms/valid-parentheses.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {string} digits
3+
* @return {string[]}
4+
*/
5+
var letterCombinations = function (digits) {
6+
if (!digits.length) return [];
7+
const result = [];
8+
const map = [
9+
"", // 0
10+
"", // 1
11+
"abc", // 2
12+
"def", // 3
13+
"ghi", // 4
14+
"jkl", // 5
15+
"mno", // 6
16+
"pqrs", // 7
17+
"tuv", // 8
18+
"wxyz", // 9
19+
];
20+
let str = "";
21+
22+
const backtracking = (digits, startIndex = 0) => {
23+
if (str.length === digits.length) {
24+
result.push(str);
25+
return;
26+
}
27+
for (let i = startIndex; i < digits.length; i++) {
28+
const chars = map[digits[i]];
29+
for (let j = 0; j < chars.length; j++) {
30+
str += chars[j];
31+
backtracking(digits, i + 1);
32+
str = str.slice(0, str.length - 1);
33+
}
34+
}
35+
};
36+
backtracking(digits);
37+
38+
return result;
39+
};

0 commit comments

Comments
 (0)