https://leetcode.com/problems/letter-combinations-of-a-phone-number/

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
/**
* @param {string} digits
* @return {string[]}
*/
const map = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'
}
let ret = []

const letterCombinations = (digits) => {
ret = []
if (digits.length !== 0) {
backtrack('', digits)
}
return ret
}

const backtrack = (comb, next) => {
if (next.length === 0) {
ret.push(comb)
}
else {
const digit = next[0]
const letters = map[digit]
for (let i = 0; i < letters.length; i++) {
const letter = letters[i]
backtrack(comb + letter, next.substring(1))
}
}
}