字符串的全排列
void Permute(strInput,strOutput,recursLev)
1 n <- length(strInput)
2 if recurLev = n
3 then print strOutput;
4 return;
5 for i <- 0 to n
6 do if strInput[i] has been used //used[i]
7 go to step 5, operate the next characater.
8 else
9 do strOutput[recursLev] <- strInput[i]
10 used[i] <- 1
11 Permute(strInput,strOutput,recursLev+1)
12 used[i] <- 0
下面是我用C实现的上述算了,增加了一个包装类,分配了三个数组并对输入字符串做了一些处理.
int Permute(char inString[])
{
int length,i,*used;
char *out;
length = strlen(inString);
out = (char *)malloc(length +1);
if(!out)
return 0;
out[length] = '\0';
used = (int *)malloc(sizeof(int) * length);
if(!used)
return 0;
for(i = 0;i
used[i] = 0;
}
DoPermute(inString,out,used,length,0);
free(out);
free(used);
return 1;
}
{
int i;
{
printf("%s\n",out);
return;
}
if(used[i])
continue;
out[recursLev] = in[i];
used[i] =1;
DoPermute(in,out,used,length,recursLev+1);
used[i] = 0;
}
}
void DoPermute(char in[],char out[],int used[],int length,int recursLev)
{
int i;
char preChar;
if(recursLev == length)
{
printf("%s\n",out);
return;
}
preChar = 0;
for(i = 0; i
if(used[i] ==0 &&in[i]!=preChar)
{
preChar = in[i];
out[recursLev] = in[i];
used[i] =1;
DoPermute(in,out,used,length,recursLev+1);
used[i] = 0;
}
}
}