题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab、和cba。
解法:递归实现
从字符串中选出一个字符作为排列的第一个字符,然后对剩余的字符进行全排列。如此递归下去,从而得到所有字符的全排列。
第一步:首先求所有可能出现在第一个位置的字符。
第二步:固定第一个字符,求后面所有字符的排列。
1)将a固定在第一位,求后面bc的排列,得到:“abc”和“acb”
2)将b固定在第一位,求后面ac的排列,得到:“bac”和“bca”
3)将c固定在第一位,求后面ba的排列,得到:“cba”和“cab”
代码如下:
#include <stdio.h>
#include <string.h>
void swap(char *a,char *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void Sort(char *perm,int from ,int to) {
if(to <=1) {
return ;
}
if(from == to) {
for(int i =0;i<= to;i++) {
printf("%c",perm[i]);
}
printf("\n");
}
else {
for(int j = from;j<=to;j++) {
swap(&perm[j],&perm[from]);
Sort(perm,from+1,to);
swap(&perm[j],&perm[from]);
}
}
}
int main() {
char s[4] = "abc";
int length = strlen(s);
Sort(s,0,length -1);
return 0;
}