#include<stdio.h>
#include <stdlib.h> /* qsort */
#define SWAP( x, y ,t) ( (t=x), (x=y) ,(y=t) ) //用宏定义函数的好处是支持了多种数据类型,类似于C++中的模板类,否则用函数的话,得编写
//多个函数从而支持不同的类型如int ,float ,double ,char,long ....
int count=1;
void PermutationRecursive( char list[],int i,int length)
{
int j,temp;
if(i==length)
{
printf("%d ." ,count);
for(j=0 ;j<=length;j++)
{
printf(" %c",list[j]);
}
printf("\n");
count++;
}
else
{
for( j=i ;j<=length;j++)
{
SWAP(list[i],list[j] ,temp);
PermutationRecursive(list, i+1 ,length);
SWAP(list[i],list[j],temp);
}
}
}
int compare (const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
/*
int main ()
{
int n;
int i;
scanf("%d",&i);
qsort (&values[i], 6-i, sizeof(int), compare);
for (n=i; n<6; n++)
printf ("%d ",values[n]);
return 0;
}
*/
//方案二采用非递归字典序的方法。思想来源:组合数学。也可以调用STL中的permutation
void permutation(char list[] ,int length)
{
char temp;
int i,j,k;
for( i=length; i>0 ; i--)
{
if( list[i-1]<list[i] )
{
k=i-1;
for(j=length;j>=i ;j-- )
{
if( list[j] >list[k])
{
SWAP( list[j] ,list[k] ,temp);
qsort( &list[i] ,(length+1)-i,sizeof(char ), compare);
for( ;i<=length;i++)
printf("%c ",list[i]);
printf("\n");
break;
}
}
if( list[j] >list[k])
{
for(i=0;i<=length ;i++)
{
printf("%c ",list[i]);
}
printf("\n");
i=length;
}
}
}
}
void main()
{
char str[]="1234";
permutation(str,4-1);
PermutationRecursive(str,0,3);
}
#include <stdlib.h> /* qsort */
#define SWAP( x, y ,t) ( (t=x), (x=y) ,(y=t) ) //用宏定义函数的好处是支持了多种数据类型,类似于C++中的模板类,否则用函数的话,得编写
//多个函数从而支持不同的类型如int ,float ,double ,char,long ....
int count=1;
void PermutationRecursive( char list[],int i,int length)
{
int j,temp;
if(i==length)
{
printf("%d ." ,count);
for(j=0 ;j<=length;j++)
{
printf(" %c",list[j]);
}
printf("\n");
count++;
}
else
{
for( j=i ;j<=length;j++)
{
SWAP(list[i],list[j] ,temp);
PermutationRecursive(list, i+1 ,length);
SWAP(list[i],list[j],temp);
}
}
}
int compare (const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
/*
int main ()
{
int n;
int i;
scanf("%d",&i);
qsort (&values[i], 6-i, sizeof(int), compare);
for (n=i; n<6; n++)
printf ("%d ",values[n]);
return 0;
}
*/
//方案二采用非递归字典序的方法。思想来源:组合数学。也可以调用STL中的permutation
void permutation(char list[] ,int length)
{
char temp;
int i,j,k;
for( i=length; i>0 ; i--)
{
if( list[i-1]<list[i] )
{
k=i-1;
for(j=length;j>=i ;j-- )
{
if( list[j] >list[k])
{
SWAP( list[j] ,list[k] ,temp);
qsort( &list[i] ,(length+1)-i,sizeof(char ), compare);
for( ;i<=length;i++)
printf("%c ",list[i]);
printf("\n");
break;
}
}
if( list[j] >list[k])
{
for(i=0;i<=length ;i++)
{
printf("%c ",list[i]);
}
printf("\n");
i=length;
}
}
}
}
void main()
{
char str[]="1234";
permutation(str,4-1);
PermutationRecursive(str,0,3);
}