按字典序進行全排列
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;
}