从1-n中选择m个数的组合个数
给定1,2,3,。。。,n(n>=1), 从n个数中选择m(m<=n)个数,求所有组合个数
递归实现:
var data = [1,2,3,4,5];
var output = [];
function outputAll(start, count){
console.log(start + "," + count); //跟踪调用过程
if(start < 0 || start > data.length || data.length - start < count || count < 0){ //参数校验
return;
}
if(count == 0){ //递归终止
console.log(output);
return;
}
var i = start;
for(i = start; i < data.length && data.length - i >= count; ++i){ //核心递归 "根 左 右"的访问深度优先 多叉树递归
output.push(data[i]);
outputAll(i + 1, count - 1);
output.pop();
}
}
outputAll(1,2);
outputAll(0, 5);