前端算法之组合
k=0或者S.length===k返回当前解
// S :数组,需要求组合的集合
// k : 取出元素个数
function combination(S, k) {
if (k === 0 || S.length === k) {
return [S.slice(0, k)]
}
const [first, ...others] = S
let r = []
r = r.concat(combination(others, k - 1).map(c => [first, ...c])) // r.concat( first 和 combination(S, k-1) 每项组合 )
r = r.concat(combination(others, k))
return r
}
const S = ['A', 'B', 'C', 'D']
console.log(combination(S, 2))

浙公网安备 33010602011771号