-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
39 lines (39 loc) · 729 Bytes
/
Copy pathmain.js
File metadata and controls
39 lines (39 loc) · 729 Bytes
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
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
const map = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'
}
const ans = []
if (digits === '') {
return ans
}
const dfs = function (index, acc) {
if (!(digits[index] in map)) {
if (index >= digits.length - 1) {
ans.push(acc)
}
dfs(index + 1, acc)
return
}
const str = map[digits[index]]
for (let i = 0; i < str.length; i++) {
if (index === digits.length - 1) {
ans.push(acc + str[i])
} else {
dfs(index + 1, acc + str[i])
}
}
}
dfs(0, '')
return ans
};