謎題
窮舉一個數組中各個元素的排列
策略
減而治之、遞歸
JavaScript解
復制代碼 代碼如下:
/**
* Created by cshao on 12/23/14.
*/
function getPermutation(arr) {
if (arr.length == 1) {
return [arr];
}
var permutation = [];
for (var i=0; i<arr.length; i++) {
var firstEle = arr[i];
var arrClone = arr.slice(0);
arrClone.splice(i, 1);
var childPermutation = getPermutation(arrClone);
for (var j=0; j<childPermutation.length; 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' ] ]