-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path017_letterCombinations.js
More file actions
84 lines (80 loc) · 2.01 KB
/
Copy path017_letterCombinations.js
File metadata and controls
84 lines (80 loc) · 2.01 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 电话号码的字母组合
// 解法1,用reduce。输出两两数组的全排列
var letterCombinations = function(digits) {
if (!digits.length) return [];
let multiply = (arr1, arr2) => {
let innerRes = []
for (let i = 0, len1 = arr1.length; i < len1; ++i) {
for (let j = 0, len2 = arr2.length; j < len2; ++j) {
innerRes.push(arr1[i]+arr2[j])
}
}
return innerRes
}
let arr = [
[],
[],
['a','b','c'],
['d','e','f'],
['g','h','i'],
['j','k','l'],
['m','n','o'],
['p','q','r','s'],
['t','u','v'],
['w','x','y','z']
]
return digits.split('').reduce((prev, cur) => {
return multiply(prev, arr[Number(cur)])
}, [''])
};
// 解法二:回溯
var letterCombinations = function (digits) {
if (!digits.length) return [];
const dfs = (level, path) => {
// terminator
if (level === digits.length) {
res.push(path.join(''));
return;
}
// process
const selectors = map.get(digits[level]);
for (let i = 0; i < selectors.length; ++i) {
path.push(selectors[i]);
dfs(level + 1, path);
path.pop();
}
}
const map = new Map([
['2', 'abc'], ['3', 'def'], ['4', 'ghi'],
['5', 'jkl'], ['6', 'mno'], ['7', 'pqrs'],
['8', 'tuv'], ['9', 'wxyz'],
]);
const res = [];
dfs(0, []);
return res;
}
// 优化下写法
var letterCombinations = function(digits) {
if (!digits.length) return [];
const dfs = (index, path) => {
if (index === digits.length) {
res.push(path.join(''));
return;
}
const chs = map.get(digits[index]);
for (const ch of chs) {
dfs(index + 1, [...path, ch]);
}
}
const map = new Map([
['2', 'abc'], ['3', 'def'],
['4', 'ghi'], ['5', 'jkl'], ['6', 'mno'],
['7', 'pqrs'], ['8', 'tuv'], ['9', 'wxyz'],
]);
const res = [];
dfs(0, []);
return res;
};
// --- test ---
console.log(letterCombinations("234"));
console.log(letterCombinations("9"));