全排列(总结)

按字典序进行全排列

1.对1~n进行全排列(递归)

#include<stdio.h>
int a[6];
int visited[6];
int n;

void dfs(int position)
{
	if(position == n+1)
	{
		for(int i = 1;i <= n;i ++)
		printf("%d",a[i]);
		printf("\n");
		return;
	}
	for(int i = 1;i <= n;i ++)
	{
		if(!visited[i])
		{
			a[position] = i;
			visited[i] = 1;
			dfs(position+1);
			visited[i] = 0;
		}
	}
}

int main()
{
	scanf("%d",&n);
	dfs(1);
	return 0;
}

2.对n个不相同的数进行全排列
#include<stdio.h>
int A[] = {2,5,9};//对A进行全排列 
int B[3];//存放全排列
int n = 3;//数组长度 

void print_permutation(int position) 
{
	if(position == n) 
	{
		for(int i = 0;i < n;i ++)
		printf("%d",B[i]);
		printf("\n");
		return;
	}
	for(int i = 0;i < n;i ++)
	{
		int ok = 1;
		for(int j = 0;j < position;j ++)
		if(B[j] == A[i])
		{
			ok = 0;
			break;
		}
		if(ok)
		{
			B[position] = A[i];
			print_permutation(position+1);
		}
	}
}

int main()
{
	print_permutation(0);
	return 0;
}

3.对n个有重复的数进行排列
#include<stdio.h>
int A[] = {2,7,7};//对A进行全排列 
int B[3];//对每次排列的记录 
int n = 3;//排列数组的长度

void print_permutation(int position) 
{
	if(position == n)
	{
		for(int i = 0;i < n;i ++)
		printf("%d",B[i]);
		printf("\n");
		return;
	}
	for(int i = 0;i < n;i ++)
	if(!i || A[i] != A[i-1])
	{
		int c1 = 0;
		int c2 = 0;
		for(int j = 0;j < position;j ++)
		if(A[i] == B[j]) c1 ++;
		for(int j = 0;j < n;j ++)
		if(A[i] == A[j]) c2 ++;
		if(c1 < c2)
		{
			B[position] = A[i];
			print_permutation(position+1);
		}
	}
}

int main()
{
	print_permutation(0);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值