排列组合程序
来源:互联网 发布:软件设计师中级试题 编辑:程序博客网 时间: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;}
- 排列组合程序
- 排列组合程序
- 排列组合的小程序
- 计算排列组合程序片段
- 计算排列组合的C++程序
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 排列组合
- 批处理:同文件名查找并替换
- 第 3 章 Beans, BeanFactory和ApplicationContext
- Python 3.0 beta 1 变化大,更简洁、更统一
- chmod
- Prototype 简介
- 排列组合程序
- 《人生中一定要读的几本》
- javascript 读取客户端MAC地址、IP地址、主机名称
- Apress.Beginning.SQL.Server.2005.Express.for.Developers.Feb.2007.eBook-BBL
- 奇怪的Dotnetnuke网页乱码问题
- Understanding the linux kernel-ch1-overview
- Understanding the linux kernel-ch2-Memory addressing
- 四核CPU玩魔兽争霸蓝屏错误
- Sql Server 常用函数