排列组合程序

来源:互联网 发布:软件设计师中级试题 编辑:程序博客网 时间:2024/05/17 04:31

今天忽然想起高中最基本的排列组合公式,想起用程序实现一下将排列组合各项列出来的功能。由于是递归写法,还是调试了一些时候才搞出来,不过感觉写法还是比较简洁的,记录在这里,还有改进余地。

 

typedef std::vector<int> IntVec;typedef IntVec::iterator IntVecIter;//组合数的递归算法//begin is the index you want to start with, start elem will be included;//end is the index you want to end with, end elem will be included;void fetch(int ay[],int begin,int end,int select_cnt){if (select_cnt==1){total+=(end-begin+1);return;}else{select_cnt--;for (int i=begin;i<=end;i++){if(end-i+1>=select_cnt) //left cnt should enoughfetch(ay,i+1,end,select_cnt);}}}//排列数的递归算法void fetch2(IntVec& v,int select_cnt){if (select_cnt==1){total+=v.size();return;}else{select_cnt--;for (int i=0;i<v.size();i++){//create a new ay which remove the i th elemIntVec vv=v;IntVecIter x=&vv[i];vv.erase(x);fetch2(vv,select_cnt);}}}//组合数的理论算法int count(int m,int n){if (n<m){return -1;}int x=m,y=n;for (int i=0;i<m-1;i++){y*=(--n);}for (m--;m>1;m--){x*=m;}return y/x;}//排列数的理论算法int count2(int m,int n){if (n<m){return -1;}int y=n;for (int i=0;i<m-1;i++){y*=(--n);}return y;}int total=0;int main(void){int s=8;int t=3;//int x=count(t,s);//int* a=new int[s];//fetch(a,0,s-1,t);//printf("theory result is: %d my result is: %d/n",x,total);IntVec v(s,0);fetch2(v,t);int y=count2(t,s);printf("theory result is: %d my result is: %d/n",y,total);return 0;}
原创粉丝点击