问题描述:输入一个数字n,提供一个排列组合方法combination(n),输出所有排列的可能,比如:combination(2) -> [1, 2]、[2, 1]; combination(3) -> [1,2,3]、[1,3,2]、[2,1,3]、[2,3,1]、[3,1,2]、[3,2,1]
解决方法:
const combination = n => {
const aryNumber = Array.from({ length: n }).map((e, i) => i + 1)
const sortedNumber = aryNumber.sort((e1, e2) => e1 - e2)
const lastNumber = sortedNumber.slice(-1)
const sortedRestNumberWithoutLastNumberDesc = sortedNumber.slice(0, -1).sort((e1, e2) => e2 - e1)
const combineNumWithAry = (n, ary) => {
const aryRtn = []
const expandAry = ary.map(item => Array.from({ length: item.length * 2 + 1 }).map((e, i) => i & 1 ? item[(i - 1) / 2] : ''))
for (let i = 0, lR = expandAry.length; i < lR; i++) {
for (let j = 0, lC = expandAry[i].length; j < lC; j++) {
if (!expandAry[i][j]) {
aryRtn.push([...expandAry[i].slice(0, j), n, ...expandAry[i].slice(j + 1)])
}
}
}
return aryRtn.map(e => e.filter(item => item !== ''))
}
let aryRtn = [lastNumber]
for (let i = 0, len = sortedRestNumberWithoutLastNumberDesc.length, item; i < len; i++) {
item = sortedRestNumberWithoutLastNumberDesc[i]
aryRtn = combineNumWithAry(item, aryRtn)
}
console.log(aryRtn)
}