Skip to content

Commit 567984a

Browse files
committed
17. Letter Combinations of a Phone Number
1 parent 96bb9f9 commit 567984a

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) [🟡](## "Medium")
2+
3+
## Description:
4+
5+
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.
6+
7+
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
8+
9+
2: 'abc'
10+
3: 'def'
11+
4: 'ghi'
12+
5: 'jkl'
13+
6: 'mno'
14+
7: 'pqrs'
15+
8: 'tuv'
16+
9: 'wxyz'
17+
18+
### Example 1:
19+
20+
Input: digits = "23"
21+
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
22+
23+
### Example 2:
24+
25+
Input: digits = ""
26+
Output: []
27+
28+
### Example 3:
29+
30+
Input: digits = "2"
31+
Output: ["a","b","c"]
32+
33+
### Constraints:
34+
35+
* `0 <= digits.length <= 4`
36+
* `digits[i]` is a digit in the range `['2', '9']`.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {string} digits
3+
* @return {string[]}
4+
*/
5+
const map = {
6+
2: 'abc',
7+
3: 'def',
8+
4: 'ghi',
9+
5: 'jkl',
10+
6: 'mno',
11+
7: 'pqrs',
12+
8: 'tuv',
13+
9: 'wxyz',
14+
};
15+
16+
export default function letterCombinations(digits, result = [], idx = 0, str = '') {
17+
if (!digits) return [];
18+
19+
if (idx === digits.length) {
20+
result.push(str);
21+
return;
22+
} else {
23+
let letters = map[digits[idx]];
24+
for (let i = 0; i < letters.length; i++) {
25+
letterCombinations(digits, result, idx + 1, str + letters[i]);
26+
}
27+
}
28+
29+
return result;
30+
};
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import solution from './solution';
2+
3+
describe('17. Letter Combinations of a Phone Number', () => {
4+
const cases = [
5+
['23', ['ad','ae','af','bd','be','bf','cd','ce','cf']],
6+
['', []],
7+
['2', ['a','b','c']],
8+
];
9+
10+
for (const [i, [input, expected]] of cases.entries()) {
11+
it(`Case ${i + 1}`, () => {
12+
expect(solution(input)).toStrictEqual(expected);
13+
});
14+
}
15+
});

0 commit comments

Comments
 (0)