排列组合算法
2022-8-9 算法
# 排列
function arrangement(
remainItems,
count = remainItems.length,
arrangementItems = []
) {
let res = [];
if (count > remainItems.length) count = remainItems.length;
if (!count) {
res = [[...arrangementItems]];
} else {
let length = remainItems.length;
for (let index = 0; index < length; index++) {
arrangementItems.push(remainItems[index]);
remainItems.splice(index, 1);
let data = arrangement(remainItems, count - 1, arrangementItems);
res.push(...data);
remainItems.splice(index, 0, arrangementItems.pop());
}
}
return res;
}
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
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
# 组合
function combination(
remainItems,
count = remainItems.length,
combinationtItems = []
) {
let res = [];
if (count > remainItems.length) count = remainItems.length;
if (!count) {
res = [[...combinationtItems]];
} else {
let length = remainItems.length;
for (let index = 0; index <= length - count; index++) {
combinationtItems.push(remainItems[index]);
let data = combination(
remainItems.slice(index + 1),
count - 1,
combinationtItems
);
res.push(...data);
combinationtItems.pop();
}
}
return res;
}
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
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