-
Notifications
You must be signed in to change notification settings - Fork 108
/
数组的排列组合.js
45 lines (43 loc) · 1.15 KB
/
数组的排列组合.js
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
// 全排列
function Permutations (target, size, origin) {
var _arr = []
function getArrange(target, nums, ret) {
if (nums === 1) {
for (var i = 0; i < target.length; i++) {
var tmp = ret.slice();
tmp.push(target[i]);
_arr.push(tmp);
}
} else {
nums -= 1;
for (var i = 0; i < target.length; i++) {
var tmp = ret.slice();
var newTarget = target.slice();
tmp.push(target[i]);
newTarget.splice(i, 1);
getArrange(newTarget, nums, tmp);
}
}
}
getArrange(target, size, origin);
return _arr;
}
Permutations([1, 2, 3], 2, [])
// 排列组合
function Permutations (arr, size) {
var ret = [];
function getRet(origin, target, size) {
if (size === 0) {
ret[ret.length] = origin;
return;
}
for (var i = 0; i <= target.length - size; i++) {
var tmp = origin.slice();
tmp.push(target[i]);
getRet(tmp, target.slice(i + 1), size - 1);
}
}
getRet([], arr, size);
return ret;
}
Permutations([1, 2, 3, 4], 3)