给定字符串'abc',输出该字符串的全排列。
['abc','acb','bac','bca','cba','cab']
递归实现:
function permutation (str) {
let arr = [...str];
let result = [];
function loop(index) {
if (index === arr.length - 1) {
result.push([...arr].join(''));
return;
}
for(let i = index; i < arr.length; i++) {
[arr[index],arr[i]] = [arr[i],arr[index]];
loop(index + 1);
[arr[index],arr[i]] = [arr[i],arr[index]];
}
}
loop(0);
return result;
}
console.log(permutation('abc'));
// [ 'abc', 'acb', 'bac', 'bca', 'cba', 'cab' ]
网友评论