1,2,3,...,N,把每种排列都输出,一共有N!种排列。
例如:1,2,3,那么输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int can_place(int *A, int i, int pos)
{
int res=1;
for(int j=0; j<pos; j++)
{
if(A[j]==i)
{
//once found j has already existed, then break and return false
res=0;
break;
}
}
return(res);
}
void hjd_permutation(FILE * fp, int *A, int N, int pos)
{
if(pos<N)
{
for(int i=1; i<=N; i++)
{
if(can_place(A, i, pos))
{
A[pos]=i;
hjd_permutation(fp, A, N, pos+1);
}
}
}
else
{
//
fprintf(fp, "\nPermutation:\n");
for(int np=0; np<N; np++)
{
fprintf(fp, "%d\t", A[np]);
}
}
}
int main(int argc, char * argv[])
{
int A[5]= {0};
FILE * fp = fopen("./permutation_out.txt", "w+");
if(NULL!=fp)
{
hjd_permutation(fp, A, 5, 0);
}
fclose(fp);
}