forked from jeantimex/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletter-combinations-of-a-phone-number.js
53 lines (46 loc) · 1.08 KB
/
letter-combinations-of-a-phone-number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Letter Combinations of A Phone Number
*
* Given a digit string, return all possible letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given below.
*
* 0: ' '
* 1: ''
* 2: abc
* 3: def
* 4: ghi
* 5: jkl
* 6: mno
* 7: pars
* 8: tuv
* 9: wxyz
*
*
* Input:Digit string "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
*/
const keyboard = [' ', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
/**
* @param {string} digits
* @return {string[]}
*/
const letterCombinations = digits => {
if (!digits) {
return [];
}
const results = [];
backtracking(digits, 0, '', results);
return results;
};
const backtracking = (digits, start, solution, results) => {
if (start === digits.length) {
return results.push(solution);
}
const index = parseInt(digits[start]);
const keys = keyboard[index];
for (let i = 0; i < keys.length; i++) {
backtracking(digits, start + 1, solution + keys[i], results);
}
};
export default letterCombinations;