字符串的全排列

来源:互联网 发布:淘宝1钻店铺出售 编辑:程序博客网 时间:2024/05/16 08:08

对于一个字符序列,要得到它的全排列,可以从第一字符开始,每个字符分别和它后面的字符交换。面试题经常用此题考察递归的实现,实现代码如下:

 

#include <string>#include <iostream>using namespace std;void swap(char* a, char* b){char temp = *a;*a = *b;*b = temp;}//index is the current number of the string,total is the sum of the stringvoid AllRange(char* Ptrch, int index, int total){if (index == total){static long int s = 1;cout << s << ": " << Ptrch << endl;s++;}else{for (int i = index; i <= total; i++){swap(Ptrch + index,Ptrch +i);AllRange(Ptrch,index + 1,total);swap(Ptrch + index,Ptrch +i);}}}int main(){char str[] = "abcde";AllRange(str,0,strlen(str) - 1);//The end of "Ptrch" is NULL return 0;}


 

原创粉丝点击