m选n组合
2018-04-18 本文已影响0人
JacobMa1996
最近需求,要写排列组合算法,首先第一步是m个元素中选n个元素进行组合,也就是数学中C(m,n);方法有多种。
递归
let arr = [1,2,3]
function combination(arr, nLen, m, singleArr, list) {
if (m === 0) {
let arrCopy = []
for (let j = 0; j < singleArr.length; j++) {
arrCopy[j] = singleArr[j]
}
list.push(arrCopy)
return
}
for (let i = nLen; i >= m; --i) {
singleArr[m - 1] = arr[i - 1]
combination(arr, i - 1, m - 1, singleArr, list)
}
}
function getArrlist (arr, num) {
let singleArr = []
let list = []
combination(arr, arr.length, num, singleArr, list)
return list
}
let list = getArrlist(arr, 2) // [2,3] [1,3] [1,2]