/**
* 描述:求一个无重复数组的全排列数组,类似数学中的排列组合
* 解题思路:递归调用,第一个数的情况是C1/n 第二个数是C1/n-1...
* @param {剩余数组} surplusArr
* @param {当前数组} curentArr
* @param {全部数据} allArr
* @returns
*/
function doCombinationCallback (surplusArr, curentArr = [], allArr = []) {
if (surplusArr && surplusArr.length === 0) {
allArr.push(curentArr)
}
for (let i = 0; i < surplusArr.length; i++) {
let otherArr = surplusArr.filter((item, index) => index !== i)
let curArr = [...curentArr, surplusArr[i]]
doCombinationCallback(otherArr, curArr, allArr)
}
return allArr
}
console.log(doCombinationCallback([1, 2, 3, 4]))
结果
[
[ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ],
[ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ],
[ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ],
[ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ],
[ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ],
[ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ],
[ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ],
[ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ],
[ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
[ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ],
[ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ],
[ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ]
]
【每日一题】数组全排列