AgPro

导航

排列和组合--递归

#include <iostream>
#include <algorithm>
using namespace std;

int N,M;

//Pemute--------------------
void Perm( int x[], int n, int k )
{
	int i;
	if ( k == n-1 )
	{
		for ( i=0; i<n; i++ )
			cout << x[i] << " ";
		cout << endl;
	}
	else
	{
		for ( i=k; i<n; i++ )
		{
			swap(x[k],x[i]);
			Perm(x,n,k+1);
			swap(x[k],x[i]);
		}
	}
}


//Combine--------------------
void Comb( int x[], int n, int m )   
 {
	for( int k=n; k>=m; k-- )
	{
		x[m] = k+1;
		if(m==0)
		{
			for( int i=0; i<M; i++)
				cout << x[i] << " ";
			cout << endl;		
		}
		else
			Comb(x,k-1,m-1);
	}   
}

int main()
{
	N=4;M=2;

	int x[4] = {1,2,3,4};
	Perm(x,N,0);

	int y[4];
	Comb(y,N-1,M-1);

	return 0;
}

posted on 2010-06-11 11:30  AgPro  阅读(179)  评论(0编辑  收藏  举报