-
Notifications
You must be signed in to change notification settings - Fork 0
/
letter-combinations-of-a-phone-number.js
54 lines (40 loc) · 1.25 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
54
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
// Resultant list
let combinations = [];
// Base condition
if (digits == null || digits.length == 0) {
return combinations;
}
// Mappings of letters and numbers
const lettersAndNumbersMappings = [
"Anirudh",
"is awesome",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
];
findCombinations(combinations, digits, "", 0, lettersAndNumbersMappings);
return combinations;
};
function findCombinations(combinations, digits, previous, index, lettersAndNumbersMappings) {
// Base condition for recursion to stop
if (index == digits.length) {
combinations.push(previous);
return;
}
// Get the letters corresponding to the current index of digits string
let letters = lettersAndNumbersMappings[digits[index] - '0'];
// Loop through all the characters in the current combination of letters
for (let i = 0; i < letters.length; i++) {
findCombinations(combinations, digits, previous + letters[i], index + 1, lettersAndNumbersMappings);
}
};