我学习全排列时看的觉着比较好网址:
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;
}