Puzzles
The arrangement of each element in an array
Strategy
The reduction of the rule and the recursion
JavaScript solution
Copy Code code as follows:
/**
* 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);
Results
Copy Code code as follows:
[[' A ', ' B ', ' C '],
[' A ', ' C ', ' B '],
[' B ', ' A ', ' C '],
[' B ', ' C ', ' a '],
[' C ', ' A ', ' B '],
[' C ', ' B ', ' a ']]