C++递归全排列

我学习全排列时看的觉着比较好网址:

        http://blog.csdn.net/summerxiachen/article/details/60579623


        http://blog.csdn.net/lemon_tree12138/article/details/50986990


我的全排列代码(C++):

#include<iostream>
using namespace std;

int arr[3]={0,1,2};
void swap(int x, int y)
{
	int t= arr[x];
	arr[x]=arr[y];
	arr[y]=t;
}
void fun(int x)
{
	if(x==3)//输出
	{
		for(int i=0; i<3; i++)
			cout<<arr[i]<<" ";
		cout<<endl;
	}

	for(int i=x; i<3; i++)
	{
		swap(x,i);
		fun(x+1);
		swap(x,i);
	}
}
int main()
{	
	fun(0);
	return 0;
}


我的全排列模板:

int arr[N];  //目标数组
void swap(int x, int y)  //数组x,y位置的数交换函数
{
	int t= arr[x];
	arr[x]=arr[y];
	arr[y]=t;
}
void fun(int x)
{
	if(x==3)//输出  或者执行相关操作
	{	}

	for(int i=x; i<3; i++)//递归
	{
		swap(x,i);
		fun(x+1);
		swap(x,i);
	}
}
int main()
{	
	fun(0);//全排列入口
	return 0;
}

顺序全排列模板:

#include<iostream>
using namespace std; 

int arr[4]={1,2,3,4};
void swap1(int x, int y)
{
	int t;
	if(x>y)
	{
		t=x; x=y; y=t;
	}
	for(int i=x; i<y; i++)
	{
		t=arr[i];
		arr[i]=arr[y];
		arr[y]=t;
	}
}
void swap2(int x, int y)
{
	int t;
	if(x>y)
	{
		t=x; x=y; y=t;
	}
	for(int i=y-1; i>=x; i--)
	{
		t=arr[i];
		arr[i]=arr[y];
		arr[y]=t;
	}
}

void fun(int x)
{
	if(x==4)
	{
		for(int i=0;i<4; i++)
			cout<<arr[i]<<" ";
		cout<<endl;
	}
	for(int i=x; i<4; i++)
	{
		swap1(i,x);
		fun(x+1);
		swap2(i,x);
	}
}
int main()
{
	fun(0);
	return 0;
} 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值