/×
采用递归算法,每次将第一个位置的字符与后面的字符进行交换,然后得到后面n-1个元素的全排列
×/
1 #include<stdio.h>
2
3 //字符串的全排列
4
5 void permutation(char *pStr,char *pbegain) {
6 if(pStr==NULL) return;
7 if(*pbegain == '\0') {
8 printf("%s\n",pStr);
9 }
10 else {
11 char *ch;
12 for(ch=pbegain;*ch!='\0';ch++) {
13 char node = *pbegain;
14 *pbegain = *ch;
15 *ch = node;
16 permutation(pStr,pbegain+1);
17 node = *pbegain;
18 *pbegain = *ch;
19 *ch = node;
20 }
21 }
22 }
23
24
25
26 void main() {
27 char a[4] ="abc";
28 permutation(a,a);
29 }
/*上述算法存在一个问题:当字符串中存在相同的字符时,会出现重复:如字符串为:test的时候,会有重复的字符串输出。为了解决上述问题:在交换字符的时候,需要加一个判断,即将要交换的字符是否相同,如果相同,则没必要交换。结果如下:*/
1 #include<stdio.h>
2
3 //字符串的全排列
4
5 void permutation(char *pStr,char *pbegain) {
6 if(pStr==NULL) return;
7 if(*pbegain == '\0') {
8 printf("%s\n",pStr);
9 }
10 else {
11 char *ch;
12 for(ch=pbegain;*ch!='\0';ch++) {
13 if(ch!= pbegain && *ch == *pbegain)
14 continue;
15 char node = *pbegain;
16 *pbegain = *ch;
17 *ch = node;
18 permutation(pStr,pbegain+1);
19 node = *pbegain;
20 *pbegain = *ch;
21 *ch = node;
22 }
23 }
24 }
25
26
27
28 void main() {
29 char a[7] ="test";
30 permutation(a,a);
31 }
不过这样还是会导致有重复值,可以采用hash或者其他方法进行结果处理