(function(){ var ret = new Array(); var A = function a(str){ if(str == undefined || str == null){return new Array();} if(str.length < 2) {return new Array(str);} if(str.length == 2) {return new Array(str[0]+str[1],str[1]+str[0]);} for(var k = 0;k < str.length; k++){ var current = str[k]; if(k == 0){ sub = str.substr(1,str.length-1); } else if(k == str.length-1){ sub = str.substr(0,str.length-1); } else{ var sub1 = str.substr(0,k); var sub2 = str.substr(k+1,str.length-1); sub = sub1+sub2; } console.log("sub : " + sub + ", current : " + current); var arr = a(sub); var r = new Array(); for(var i =0 ;i < arr.length; i++){ var ar = arr[i]; for(var j = 0 ;j < arr.length + 1; j++){ var tmp = insert(ar,current,j); if(ret.indexOf(tmp) == -1 ){ret.push(tmp);r.push(tmp);} } } return r; } }; var insert = function (oristr,s,p){ if(p == 0){ return s+oristr; } if(p >= oristr.length){ return oristr + s; } else{ var sub1 = oristr.substr(0,p); var sub2 = oristr.substr(p,oristr.length-1); return sub1+s+sub2; } }; var r = A("abcde"); console.log(r); })();
全排列算法 --javascript 实现,布布扣,bubuko.com
原文地址:http://blog.csdn.net/csharp25/article/details/28258135