Description
Generate the complete permutation of 1..N
Input
Each input file contains only one non-negative integer N (0< N < 9)
Output
Output N! Lines, according to lexicographic order.
Sample Input
3
Sample Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Source
xmu
就是按照字母序写个1到n的全排列。
#include<stdio.h>
#define maxn 10
int str[maxn];
void pe(int n,int *a ,int cur)
{
int i,j;
if(cur==n)
{
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else
{
for(i=1;i<=n;i++)
{
int ok=1;
for(j=0;j<cur;j++)
{
if(a[j]==i)ok=0;
}
if(ok)
{
a[cur]=i;
pe(n,a,cur+1);
}
}
}
}
int main()
{
int n;
int a[maxn];
scanf("%d",&n);
pe(n,a,0);
return 0;
}
上面的代码仅仅是针对这道题目,如果对于任意的数列进行按照字母序全排列需要修改一些地方代码如下
#include<stdio.h>
#include<algorithm>
using namespace std;
#define maxn 10
int str[maxn];
void pe(int n,int *a ,int cur)
{
int i,j;
if(cur==n)
{
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else
{
for(i=0;i<n;i++)
{
if(!i||str[i]!=str[i-1])// 对于数列中相同的数字不进行重复的排列
{
int ok=1;
for(j=0;j<cur;j++)
{
if(a[j]==str[i])ok=0;
}
if(ok)
{
a[cur]=str[i];
pe(n,a,cur+1);
}
else
{
int c1=0,c2=0;
for(j=0;j<cur;j++)
{
if(a[j]==str[i])c1++;
}
for(j=0;j<n;j++)
if(str[i]==str[j])c2++;//针对数列在的重复数字
if(c1<c2)
{
a[cur]=str[i];
pe(n,a,cur+1);
}
}
}
}
}
}
int main()
{
int n;
int a[maxn];
scanf("%d",&n);
int i,j;
for(i=0;i<n;i++)
scanf("%d",str+i);
sort(str,str+n);
pe(n,a,0);
return 0;
}
上述代码稍微修改便可以变成求给定序列的下一个排列。
#include<stdio.h>
#include<algorithm>
using namespace std;
#define maxn 10
//int a[maxn];
int str[maxn];
void pe(int n,int *a ,int cur)
{
int i,j;
if(cur==n)
{
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else
{
for(i=0;i<n;i++)
{
if(!i||str[i]!=str[i-1])
{
int ok=1;
for(j=0;j<cur;j++)
{
if(a[j]==str[i])ok=0;
}
if(ok)
{
a[cur]=str[i];
pe(n,a,cur+1);
return ;
}
else
{
int c1=0,c2=0;
for(j=0;j<cur;j++)
{
if(a[j]==str[i])c1++;
}
for(j=0;j<n;j++)
if(str[i]==str[j])c2++;
if(c1<c2)
{
a[cur]=str[i];
pe(n,a,cur+1);
return ;
}
}
}
}
}
}
int main()
{
int n;
int a[maxn];
int b[maxn];
scanf("%d",&n);
int i,j;
for(i=0;i<n;i++)
{
scanf("%d",str+i);
}
int maxmin=999999,index;
for(i=n-2;i>=0;i--)
{
for(j=i+1;j<n;j++)
{
if(str[i]<str[j]&&str[j]<maxmin)
{
maxmin=str[j];
index=i;
}
}
if(maxmin!=999999)
break;
}
for(i=0;i<index;i++)
a[i]=str[i];
a[i]=maxmin;
sort(str,str+n);
if(maxmin==999999)
printf("-1\n");
else
pe(n,a,index+1);
return 0;
}