用递归实现全排列
用递归实现全排列
#include
#include
char* Result;
int N;
void PP(char alphain[],int k)
{
int i,j,s;
char* alphaout;
if(k==1)
{
Result[N-1]=alphain[0];
for(i=0;i
printf("%c",Result[i]);
}
printf("n");
}
else
{
alphaout=(char*)malloc(sizeof(char)*(k-1));
for(i=0;i
s=0;
Result[N-k]=alphain[i];
for(j=0;j
if(j!=i)
{
alphaout[s]=alphain[j];
s++;
}
}
PP(alphaout,k-1);
}
}
}
void main()
{
int i;
char* alphabet;
printf("input N:");
scanf("%d",&N);
alphabet=(char*)malloc(sizeof(char)*N);
Result=(char*)malloc(sizeof(char)*N);
for(i=0;i
alphabet[i]=(char)(i+65);
}
PP(alphabet,N);
}
非递归算法
#include j=i;
// N must be greater than 1
#define N 5
#define swap(a,b) (a)=(a)-(b),(b)=(b)+(a),(a)=(b)-(a);
void output(int p[]) {
static int count=0;
printf("%5d:",++count);
for(int i=0;i
}
int next(int p[]) {
int j;
int i=N-1;
while (i>0) {
i--;
if (p[i+1]
while (++j
swap(p[i],p[j-1]);
// i+1 ... N-1 (N-1-i-1+1 = N-i-1 number in total)
for(j=i+1;j<(i+1 + N-1 + 1)/2;j++) {
swap(p[j],p[N-(j-i)]);
}
return 1;
}
return 0;
}
int main() {
int p[N];
// init
for(int i=0;i
// loop for next
while (next(p)) {
output(p);
}
return 0;
}