求C(n,m)组合问题

来源:互联网 发布:尘埃3mac汉化补丁 编辑:程序博客网 时间:2024/05/16 19:23

2014年IGT校园招聘C++试卷最后一道编程题:

有1,2,3……n个数,从这n个数中随机选出m个数,列举出所有可能的情况。

例如n=5,n=3,则输出:

5 4 3

5 4 2

5 4 1

5 3 2

5 3 1

5 2 1

4 3 2

4 3 1

4 2 1

3 2 1

本题可以用递归解决,下面是我的代码,但是耦合性太高,而且内存有点浪费。

#include <iostream>#define Max 100using namespace std;int b[Max];/*  M 为C(n,m)中的m,在递归过程中他的值不发生变化  m 初始值为M,在递归过程中不断减小,直至为1 */void combination(int n,int m,int M){if(m==1) for(int i=n;i>0;i--) {b[0]=i;for(int j=M-1;j>=0;j--)cout<<b[j]<<" ";cout<<endl;}else {for(int i=n;i>=m;i--){b[m-1]=i;combination(i-1,m-1,M);}}}int main(){combination(5,3,3);return 0;}

原创粉丝点击