排列组合程序

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

 

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 enough

				fetch(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 elem

			IntVec 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;

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值