-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletter-combinations-of-a-phone-number_0914.html
51 lines (45 loc) · 1.35 KB
/
letter-combinations-of-a-phone-number_0914.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>letter-combinations-of-a-phone-number</title>
</head>
<body></body>
<script>
/**
* @param {string} digits
* @return {string[]}
*/
function letterCombinations(digits) {
if (digits.length === 0) return [];
const phoneMap = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
};
const result = [];
const backtrack = (combination, nextDigits) => {
// If there is no more digits to check
if (nextDigits.length === 0) {
result.push(combination);
} else {
// For the next available digit, go over the letters that the digit maps to.
let digit = nextDigits[0];
for (let letter of phoneMap[digit]) {
// Append the current letter to the combination and proceed to the next digits
backtrack(combination + letter, nextDigits.slice(1));
}
}
};
backtrack("", digits);
return result;
}
</script>
</html>