function permute(input) {
var permArr = [],
usedChars = [];
function main(input){
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
main(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr
}
return main(input);
};
console.log(permute([5, 3, 7, 1]));
转载自https://www.jb51.net/article/62524.htm
另外一种是根据字符串 来排序
function permutate(str) {
var result=[];
if(str.length==1){
return [str]
}else{
var preResult=permutate(str.slice(1));
for (var j = 0; j < preResult.length; j++) {
for (var k = 0; k < preResult[j].length+1; k++) {
var temp=preResult[j].slice(0,k)+str[0]+preResult[j].slice(k);
result.push(temp);
}
}
return result;
}
}
console.log(permutate("abc"));
本文介绍两种使用JavaScript实现的排列组合算法。第一种适用于数组输入,通过递归与回溯技术生成所有可能的排列。第二种算法则针对字符串输入,采用递归方式生成字符串的所有可能排列。
1081

被折叠的 条评论
为什么被折叠?



