js排列组合算法源码
function _permutation(ary) {
if(ary.length == 0) {
return [];
}
if(ary.length == 1) {
return [].concat(ary[0]);
}
let currentAry = ary.pop();
let permutations = [];
for(let i=0; i<currentAry.length; i++) {
let item = currentAry[i];
let last = _permutation([].concat(ary));
for(let j=0; j<last.length; j++) {
last[j] = [item].concat(last[j]);
}
permutations = permutations.concat(last);
}
return permutations;
}
function permutation(ary) {
return _permutation([].concat(ary).reverse());
}
~function () {
let ary = [
[1,2,3],
['a', 'b', 'c', 'd'],
['A', 'B'],
];
console.log(permutation(ary));
}()