JavaScript实现穷举排列(permutation)算法谜题解答
谜题
穷举一个数组中各个元素的排列
策略
减而治之、递归
JavaScript解
/** *Createdbycshaoon12/23/14. */
functiongetPermutation(arr){ if(arr.length==1){ return[arr]; }
varpermutation=[]; for(vari=0;i<arr.length;i++){ varfirstEle=arr[i]; vararrClone=arr.slice(0); arrClone.splice(i,1); varchildPermutation=getPermutation(arrClone); for(varj=0;j<childPermutation.length;j++){ childPermutation[j].unshift(firstEle); } permutation=permutation.concat(childPermutation); } returnpermutation; }
varpermutation=getPermutation(['a','b','c']); console.dir(permutation);