JS求组合数
获取从[0, 1, 2, ... , m]闭区间的数中任选m
个数,求其组合和组合的个数,即
\[C_n^m
\]
// 获取[1, end]闭区间的组合数
function getCombine(end, num) {
if (num > end + 1 || num === 0) {
return []
}
let set = new Set()
f(num)
/**
*
* @param round 要循环几层
* @param arr
*/
function f(round, arr = []) {
if (round === 0) return
for (let i = 1; i <= end; i++) {
if (round === 1) { // 最内层的循环
let result = [...arr, i]
if (isSet(result)) {
result = result.sort()
result = result.join(' ')
set.add(result)
}
}
f(round - 1, [...arr, i])
}
}
return Array.from(set)
}
function isSet(arr) {
return new Set(arr).size === arr.length
}
// no-log
// log
let c1 = getCombine(6, 4)
console.log(c1)
let c2 = getCombine(10,3)
console.log(c2.length)