|
| 1 | +[](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript) |
| 2 | +[](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork) |
| 3 | + |
| 4 | +## 17\. Letter Combinations of a Phone Number |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. |
| 9 | + |
| 10 | +A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +**Example 1:** |
| 15 | + |
| 16 | +**Input:** digits = "23" |
| 17 | + |
| 18 | +**Output:** ["ad","ae","af","bd","be","bf","cd","ce","cf"] |
| 19 | + |
| 20 | +**Example 2:** |
| 21 | + |
| 22 | +**Input:** digits = "" |
| 23 | + |
| 24 | +**Output:** [] |
| 25 | + |
| 26 | +**Example 3:** |
| 27 | + |
| 28 | +**Input:** digits = "2" |
| 29 | + |
| 30 | +**Output:** ["a","b","c"] |
| 31 | + |
| 32 | +**Constraints:** |
| 33 | + |
| 34 | +* `0 <= digits.length <= 4` |
| 35 | +* `digits[i]` is a digit in the range `['2', '9']`. |
| 36 | + |
| 37 | +## Solution |
| 38 | + |
| 39 | +```typescript |
| 40 | +function letterCombinations(digits: string): string[] { |
| 41 | + if (digits.length === 0) { |
| 42 | + return [] |
| 43 | + } |
| 44 | + const letters: string[] = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] |
| 45 | + const ans: string[] = [] |
| 46 | + const sb: string[] = [] |
| 47 | + findCombinations(0, digits, letters, sb, ans) |
| 48 | + return ans |
| 49 | +} |
| 50 | + |
| 51 | +function findCombinations(start: number, nums: string, letters: string[], curr: string[], ans: string[]): void { |
| 52 | + if (curr.length === nums.length) { |
| 53 | + ans.push(curr.join('')) |
| 54 | + return |
| 55 | + } |
| 56 | + for (let i = start; i < nums.length; i++) { |
| 57 | + const n = parseInt(nums.charAt(i)) |
| 58 | + for (let j = 0; j < letters[n].length; j++) { |
| 59 | + const ch = letters[n].charAt(j) |
| 60 | + curr.push(ch) |
| 61 | + findCombinations(i + 1, nums, letters, curr, ans) |
| 62 | + curr.pop() |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export { letterCombinations } |
| 68 | +``` |
0 commit comments