-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathletterCombinations.js
37 lines (30 loc) · 939 Bytes
/
letterCombinations.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
function letterCombinations(digits){
let combinations = [];
if(digits.length === 0) {
return combinations;
}
let digitToChar = new Map();
digitToChar.set('2', "abc");
digitToChar.set('3', "def");
digitToChar.set('4', "ghi");
digitToChar.set('5', "jkl");
digitToChar.set('6', "mno");
digitToChar.set('7', "pqrs");
digitToChar.set('8', "tuv");
digitToChar.set('9', "wxyz");
backtrack(0, "", digits, digitToChar, combinations);
return combinations;
}
function backtrack(i, currStr, digits, digitToChar, combinations){
if(digits.length === currStr.length) {
combinations.push(currStr);
return;
}
for (const ch of digitToChar.get(digits[i])) {
backtrack(i+1, currStr+ch, digits, digitToChar, combinations);
}
}
let digits1 = "24";
let digits2 = "";
console.log(letterCombinations(digits1));
console.log(letterCombinations(digits2));