电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
1
2
2
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if (!digits) return []
let numMap = new Map([
['1', ''],
['2', 'abc'],
['3', 'def'],
['4', 'ghi'],
['5', 'jkl'],
['6', 'mno'],
['7', 'pqrs'],
['8', 'tuv'],
['9', 'wxyz']
])
function helper(digits, output) {
let curNum = digits[0]
let curLetter = numMap.get(curNum)
if (!output.length) {
for (let i = 0; i < curLetter.length; i++) {
output.push(curLetter[i])
}
} else {
let newOutPut = []
for (let m = 0; m < output.length; m++) {
for (let n = 0; n < curLetter.length; n++) {
newOutPut.push(output[m] + curLetter[n])
}
}
output = newOutPut
}
digits = digits.slice(1)
if (digits) {
output = helper(digits, output)
}
return output
}
return helper(digits, [])
};
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
55
56
57
58
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
55
56
57
58
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number