Skip to content

Commit faf510e

Browse files
committed
feat: add Letter Combinations of a Phone Number
1 parent 3214e68 commit faf510e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ Roadmap: https://neetcode.io/roadmap
7878
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/) | Medium | [ts](./TypeScript/40.combination-sum-ii.ts) | Backtracking |
7979
| 79 | [Word Search](https://leetcode.com/problems/word-search/) | Medium | [ts](./TypeScript/79.word-search.ts) | Backtracking |
8080
| 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/description/) | Medium | [ts](./TypeScript/131.palindrome-partitioning.ts) | Backtracking |
81+
| 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) | Medium | [ts](./TypeScript/17.letter-combinations-of-a-phone-number.ts) | Backtracking |
8182

8283
### Others
8384

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
function letterCombinations(digits: string): string[] {
2+
const map = {
3+
"2": ["a", "b", "c"],
4+
"3": ["d", "e", "f"],
5+
"4": ["g", "h", "i"],
6+
"5": ["j", "k", "l"],
7+
"6": ["m", "n", "o"],
8+
"7": ["p", "q", "r", "s"],
9+
"8": ["t", "u", "v"],
10+
"9": ["w", "x", "y", "z"],
11+
};
12+
const combinations: string[][] = [];
13+
const combination: string[] = [];
14+
15+
function backtrace(index) {
16+
if (index > digits.length) {
17+
return;
18+
}
19+
if (index === digits.length) {
20+
combinations.push(combination.slice());
21+
return;
22+
}
23+
for (let i = 0; i < map[digits.charAt(index)].length; i++) {
24+
combination.push(map[digits.charAt(index)][i]);
25+
backtrace(index + 1);
26+
combination.pop();
27+
}
28+
}
29+
30+
backtrace(0);
31+
32+
if (!digits) {
33+
return [];
34+
}
35+
36+
return combinations.map((c) => c.join(""));
37+
}
38+
39+
console.log(letterCombinations("23"));

0 commit comments

Comments
 (0)