首页 > 其他 > 详细

n全排列输出和 n个数的组合(数字范围a~b)

时间:2014-08-26 19:19:16      阅读:392      评论:0      收藏:0      [点我收藏+]

n全排列输出:

int WPermutation(int num, bool bRepeat)

num表示num全排列

bRepeat标志是否产生重复元素的序列。

 

int Permutation(int n, int* A, int cur, bool bRepeat) 
{
	static int number = 0;
	if(cur == n)
	{   
		number++;
		for(int i = 0; i< n; i++)
		{
			printf("%d ", A[i]);
		}
		printf("\n");
	}
	else
	{
		for(int i = 1; i <= n; i++)
		{
			int ok = 1;
			for(int j = 0; j < cur; j++)    
			{
				if(!bRepeat)
				{
					if(A[j] == i)
					{
						ok = 0;
					}
				}
			}
			
				if(ok)
				{
					A[cur] = i;
					Permutation(n, A, cur + 1, bRepeat);
				}			

		}
	}

    return number;
}
int WPermutation(int num, bool bRepeat)
{
	printf("%d permutation(%s): %d ~ %d\n", num, bRepeat?"repeat mode":"single mode", 1, num);
	int n = num;
	int *A = (int*)malloc(n*sizeof(int));
	memset(A, 0, sizeof(n*sizeof(int)));
	int cur = 0;
	int number = Permutation(n, A, cur, bRepeat);
	delete [] A ;
	A = NULL;
	printf("over!\n");
	return number;

}


int Wpermutation(int st, int en, int n, bool bRepeat);

 n个数的组合(数字范围st~en),考虑重复元素:

n表示n个数字组合

每个数字范围:st~en

bRepeat标志是否产生重复元素的序列。

 

int Permutation(int st, int en, int n, int* A, int cur, bool bRepeat)
{
	static int number = 0;

	if(cur == n)
	{   
		number++;
		for(int i = 0; i< n; i++)
		{
			printf("%d ", A[i]);
		}
		printf("\n");
	}
	else
	{
		for(int i = st; i <= en; i++)
		{
			int ok = 1;
			for(int j = 0; j < cur; j++)
			{
				if(!bRepeat)
				{
					if(A[j] == i)
					{
						ok = 0;
					}
				}
			}

			if(ok)
			{
				A[cur] = i;
				Permutation(st, en, n, A, cur + 1, bRepeat);			
			}			

		}
	}

	return number;
}

int Wpermutation(int st, int en, int n, bool bRepeat)
{
	printf("%d permutation(%s): %d ~ %d\n", n, bRepeat?"repeat mode":"single mode", st, en);
	int num = en - st + 1;
	if(n > num)
	{
		bRepeat = true;
		printf("too many number, to be repeat mode:\n");
	}

	int *A = (int*)malloc(n*sizeof(int));
	memset(A, 0, sizeof(n*sizeof(int)));
	int cur = 0;
	int number = Permutation(st, en, n, A, cur, bRepeat);
	delete [] A ;
	A = NULL;
	printf("over!\n");
	return number;
}

n全排列输出和 n个数的组合(数字范围a~b)

原文:http://www.cnblogs.com/welen/p/3937745.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!