谜题
穷举一个数组中各个元素的排列
策略
减而治之、递归
javascript解
复制代码 代码如下:
/**
* created by cshao on 12/23/14.
*/function getpermutation(arr) {
if (arr.length == 1) {
return [arr];
}
var permutation = [];
for (var i=0; i var firstele = arr[i];
var arrclone = arr.slice(0);
arrclone.splice(i, 1);
var childpermutation = getpermutation(arrclone);
for (var j=0; j childpermutation[j].unshift(firstele);
}
permutation = permutation.concat(childpermutation);
}
return permutation;
}
var permutation = getpermutation(['a','b','c']);
console.dir(permutation);
结果
复制代码 代码如下:
[ [ 'a', 'b', 'c' ],
[ 'a', 'c', 'b' ],
[ 'b', 'a', 'c' ],
[ 'b', 'c', 'a' ],
[ 'c', 'a', 'b' ],
[ 'c', 'b', 'a' ] ]