排列组合Cnr,从n个数中取出r个并打印。原创,来自宿舍同学的笔试题。环境VC++
#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;
void printData(int i,int x,int n,vector<int>* s){//x为还需要输出x个数,i为当前的数字,n为n个数字,递归实现
s->push_back(i);
if (x==0) {
for(vector<int>::iterator iter=s->begin();iter!=s->end();iter++)
cout<<*iter<<" ";
cout<<endl;
}
if (i<=(n-x)) {
x--;
for(int k = i+1; k<=n; k++){
printData(k,x,n,s);
}
}
s->pop_back();
}
void cnr(int n,int r){
vector<int> *i=new vector<int>;
printData(1,r-1,n,i);
delete i;
}
int main(int argc, char* argv[])
{
printf("Hello World!/n");
cnr(9,4);
return 0;
}