排列组合之字符串的全排列和组合算法

 

全排列在笔试面试中很热门,因为它难度适中,既可以考察递归实现,又能进一步考察非递归的实现,便于区分出考生的水平。所以在百度和迅雷的校园招聘以及程序员和软件设计师的考试中都考到了,因此本文对全排列作下总结帮助大家更好的学习和理解。对本文有任何补充之处,欢迎大家指出。
首先来看看题目是如何要求的(百度迅雷校招笔试题)。
一、字符串的排列
用C++写一个函数, 如 Foo(const char *str), 打印出 str 的全排列,
如 abc 的全排列: abc, acb, bca, dac, cab, cba

一、全排列的递归实现

为方便起见,用123来示例下。123的全排列有123、132、213、231、312、321这六种。首先考虑213和321这二个数是如何得出的。显然这二个都是123中的1与后面两数交换得到的。然后可以将123的第二个数和每三个数交换得到132。同理可以根据213和321来得231和312。因此可以知道——全排列就是从第一个数字起每个数分别与它后面的数字交换。找到这个规律后,递归的代码就很容易写出来了:

  1. #include<iostream>  
  2. using namespace std; 
  3. #include<assert.h>  
  4.  
  5. void Permutation(char* pStr,char* pBegin) 
  6.     assert(pStr && pBegin); 
  7.  
  8.     if(*pBegin =='\0'
  9.         printf("%s\n",pStr); 
  10.     else 
  11.     { 
  12.         for(char* pCh = pBegin; *pCh !='\0'; pCh++) 
  13.         { 
  14.             swap(*pBegin,*pCh); 
  15.             Permutation(pStr, pBegin+1); 
  16.             swap(*pBegin,*pCh); 
  17.         } 
  18.     } 
  19.  
  20. int main(void
  21.     char str[] = "abc"
  22.     Permutation(str,str); 
  23.     return 0; 
  1. #include<iostream> 
  2. using namespace std; 
  3. #include<assert.h> 
  4.  
  5. void Permutation(char* pStr,char* pBegin) 
  6.     assert(pStr && pBegin); 
  7.  
  8.     if(*pBegin == '\0'
  9.         printf("%s\n",pStr); 
  10.     else 
  11.     { 
  12.         for(char* pCh = pBegin; *pCh !='\0'; pCh++) 
  13.         { 
  14.             swap(*pBegin,*pCh); 
  15.             Permutation(pStr, pBegin+1); 
  16.             swap(*pBegin,*pCh); 
  17.         } 
  18.     } 
  19.  
  20. int main(void
  21.     char str[] = "abc"
  22.     Permutation(str,str); 
  23.     return 0; 

另外一种写法:

  1. //k表示当前选取到第几个数,m表示共有多少个数  
  2. void Permutation(char* pStr,int k,int m) 
  3.     assert(pStr); 
  4.  
  5.     if(k == m) 
  6.     { 
  7.         static int num = 1; //局部静态变量,用来统计全排列的个数 
  8.         printf("第%d个排列\t%s\n",num++,pStr); 
  9.     } 
  10.     else 
  11.     { 
  12.         for(int i = k; i <= m; i++) 
  13.         { 
  14.             swap(*(pStr+k),*(pStr+i)); 
  15.             Permutation(pStr, k + 1 , m); 
  16.             swap(*(pStr+k),*(pStr+i)); 
  17.         } 
  18.     } 
  19.  
  20. int main(void
  21.     char str[] = "abc"
  22.     Permutation(str , 0 , strlen(str)-1); 
  23.     return 0; 
  1. //k表示当前选取到第几个数,m表示共有多少个数 
  2. void Permutation(char* pStr,int k,int m) 
  3.     assert(pStr); 
  4.  
  5.     if(k == m) 
  6.     { 
  7.         static int num = 1; //局部静态变量,用来统计全排列的个数 
  8.         printf("第%d个排列\t%s\n",num++,pStr); 
  9.     } 
  10.     else 
  11.     { 
  12.         for(int i = k; i <= m; i++) 
  13.         { 
  14.             swap(*(pStr+k),*(pStr+i)); 
  15.             Permutation(pStr, k + 1 , m); 
  16.             swap(*(pStr+k),*(pStr+i)); 
  17.         } 
  18.     } 
  19.  
  20. int main(void
  21.     char str[] = "abc"
  22.     Permutation(str , 0 , strlen(str)-1); 
  23.     return 0; 
如果字符串中有重复字符的话,上面的那个方法肯定不会符合要求的,因此现在要想办法来去掉重复的数列。
二、去掉重复的全排列的递归实现
由于全排列就是从第一个数字起每个数分别与它后面的数字交换。我们先尝试加个这样的判断——如果一个数与后面的数字相同那么这二个数就不交换了。如122,第一个数与后面交换得212、221。然后122中第二数就不用与第三个数交换了,但对212,它第二个数与第三个数是不相同的,交换之后得到221。与由122中第一个数与第三个数交换所得的221重复了。所以这个方法不行。

换种思维,对122,第一个数1与第二个数2交换得到212,然后考虑第一个数1与第三个数2交换,此时由于第三个数等于第二个数,所以第一个数不再与第三个数交换。再考虑212,它的第二个数与第三个数交换可以得到解决221。此时全排列生成完毕。
这样我们也得到了在全排列中去掉重复的规则——去重的全排列就是从第一个数字起每个数分别与它后面非重复出现的数字交换。下面给出完整代码:

  1. #include<iostream>  
  2. using namespace std; 
  3. #include<assert.h>  
  4.  
  5. //在[nBegin,nEnd)区间中是否有字符与下标为pEnd的字符相等 
  6. bool IsSwap(char* pBegin ,char* pEnd) 
  7.     char *p; 
  8.     for(p = pBegin ; p < pEnd ; p++) 
  9.     { 
  10.         if(*p == *pEnd) 
  11.             return false
  12.     } 
  13.     return true
  14. void Permutation(char* pStr ,char *pBegin) 
  15.     assert(pStr); 
  16.  
  17.     if(*pBegin == '\0'
  18.     { 
  19.         static int num = 1; //局部静态变量,用来统计全排列的个数 
  20.         printf("第%d个排列\t%s\n",num++,pStr); 
  21.     } 
  22.     else 
  23.     { 
  24.         for(char *pCh = pBegin; *pCh !='\0'; pCh++)  //第pBegin个数分别与它后面的数字交换就能得到新的排列   
  25.         { 
  26.             if(IsSwap(pBegin , pCh)) 
  27.             { 
  28.                 swap(*pBegin , *pCh); 
  29.                 Permutation(pStr , pBegin + 1); 
  30.                 swap(*pBegin , *pCh); 
  31.             } 
  32.         } 
  33.     } 
  34.  
  35. int main(void
  36.     char str[] ="baa"
  37.     Permutation(str , str); 
  38.     return 0; 
  1. #include<iostream> 
  2. using namespace std; 
  3. #include<assert.h> 
  4.  
  5. //在[nBegin,nEnd)区间中是否有字符与下标为pEnd的字符相等 
  6. bool IsSwap(char* pBegin ,char* pEnd) 
  7.     char *p; 
  8.     for(p = pBegin ; p < pEnd ; p++) 
  9.     { 
  10.         if(*p == *pEnd) 
  11.             return false
  12.     } 
  13.     return true
  14. void Permutation(char* pStr ,char *pBegin) 
  15.     assert(pStr); 
  16.  
  17.     if(*pBegin == '\0'
  18.     { 
  19.         static int num = 1; //局部静态变量,用来统计全排列的个数 
  20.         printf("第%d个排列\t%s\n",num++,pStr); 
  21.     } 
  22.     else 
  23.     { 
  24.         for(char *pCh = pBegin; *pCh !='\0'; pCh++)  //第pBegin个数分别与它后面的数字交换就能得到新的排列   
  25.         { 
  26.             if(IsSwap(pBegin , pCh)) 
  27.             { 
  28.                 swap(*pBegin , *pCh); 
  29.                 Permutation(pStr , pBegin + 1); 
  30.                 swap(*pBegin , *pCh); 
  31.             } 
  32.         } 
  33.     } 
  34.  
  35. int main(void
  36.     char str[] = "baa"
  37.     Permutation(str , str); 
  38.     return 0; 
OK,到现在我们已经能熟练写出递归的方法了,并且考虑了字符串中的重复数据可能引发的重复数列问题。那么如何使用非递归的方法来得到全排列了?

三、全排列的非递归实现
要考虑全排列的非递归实现,先来考虑如何计算字符串的下一个排列。如"1234"的下一个排列就是"1243"。只要对字符串反复求出下一个排列,全排列的也就迎刃而解了。
如何计算字符串的下一个排列了?来考虑"926520"这个字符串,我们从后向前找第一双相邻的递增数字,"20"、"52"都是非递增的,"26 "即满足要求,称前一个数字2为替换数,替换数的下标称为替换点,再从后面找一个比替换数大的最小数(这个数必然存在),0、2都不行,5可以,将5和2交换得到"956220",然后再将替换点后的字符串"6220"颠倒即得到"950226"。
对于像“4321”这种已经是最“大”的排列,采用STL中的处理方法,将字符串整个颠倒得到最“小”的排列"1234"并返回false。

这样,只要一个循环再加上计算字符串下一个排列的函数就可以轻松的实现非递归的全排列算法。按上面思路并参考STL中的实现源码,不难写成一份质量较高的代码。值得注意的是在循环前要对字符串排序下,可以自己写快速排序的代码(请参阅《白话经典算法之六 快速排序 快速搞定》),也可以直接使用VC库中的快速排序函数(请参阅《使用VC库函数中的快速排序函数》)。下面列出完整代码:

  1. #include<iostream>  
  2. #include<algorithm>  
  3. #include<cstring>  
  4. using namespace std; 
  5. #include<assert.h>  
  6.  
  7. //反转区间  
  8. void Reverse(char* pBegin ,char* pEnd) 
  9.     while(pBegin < pEnd) 
  10.         swap(*pBegin++ , *pEnd--); 
  11. //下一个排列  
  12. bool Next_permutation(char a[]) 
  13.     assert(a); 
  14.     char *p , *q , *pFind; 
  15.     char *pEnd = a + strlen(a) - 1; 
  16.     if(a == pEnd) 
  17.         return false
  18.     p = pEnd; 
  19.     while(p != a) 
  20.     { 
  21.         q = p; 
  22.         p--; 
  23.         if(*p < *q)  //找降序的相邻2数,前一个数即替换数  
  24.         { 
  25.              //从后向前找比替换点大的第一个数  
  26.             pFind = pEnd; 
  27.             while(*pFind < *p) 
  28.                 --pFind; 
  29.             swap(*p , *pFind); 
  30.             //替换点后的数全部反转  
  31.             Reverse(q , pEnd); 
  32.             returntrue
  33.         } 
  34.     } 
  35.     Reverse(a , pEnd);   //如果没有下一个排列,全部反转后返回false   
  36.     return false
  37.  
  38. int cmp(constvoid *a,constvoid *b) 
  39.     return int(*(char *)a - *(char *)b); 
  40. int main(void
  41.     char str[] = "bac"
  42.     int num = 1; 
  43.     qsort(str , strlen(str),sizeof(char),cmp); 
  44.     do 
  45.     { 
  46.         printf("第%d个排列\t%s\n",num++,str);  
  47.     }while(Next_permutation(str)); 
  48.     return 0; 
  1. #include<iostream> 
  2. #include<algorithm> 
  3. #include<cstring> 
  4. using namespace std; 
  5. #include<assert.h> 
  6.  
  7. //反转区间 
  8. void Reverse(char* pBegin ,char* pEnd) 
  9.     while(pBegin < pEnd) 
  10.         swap(*pBegin++ , *pEnd--); 
  11. //下一个排列 
  12. bool Next_permutation(char a[]) 
  13.     assert(a); 
  14.     char *p , *q , *pFind; 
  15.     char *pEnd = a + strlen(a) - 1; 
  16.     if(a == pEnd) 
  17.         return false
  18.     p = pEnd; 
  19.     while(p != a) 
  20.     { 
  21.         q = p; 
  22.         p--; 
  23.         if(*p < *q)  //找降序的相邻2数,前一个数即替换数  
  24.         { 
  25.              //从后向前找比替换点大的第一个数 
  26.             pFind = pEnd; 
  27.             while(*pFind < *p) 
  28.                 --pFind; 
  29.             swap(*p , *pFind); 
  30.             //替换点后的数全部反转 
  31.             Reverse(q , pEnd); 
  32.             return true
  33.         } 
  34.     } 
  35.     Reverse(a , pEnd);   //如果没有下一个排列,全部反转后返回false   
  36.     return false
  37.  
  38. int cmp(constvoid *a,constvoid *b) 
  39.     return int(*(char *)a - *(char *)b); 
  40. int main(void
  41.     char str[] = "bac"
  42.     int num = 1; 
  43.     qsort(str , strlen(str),sizeof(char),cmp); 
  44.     do 
  45.     { 
  46.         printf("第%d个排列\t%s\n",num++,str);  
  47.     }while(Next_permutation(str)); 
  48.     return 0; 
至此我们已经运用了递归与非递归的方法解决了全排列问题,总结一下就是:
1、全排列就是从第一个数字起每个数分别与它后面的数字交换。
2、去重的全排列就是从第一个数字起每个数分别与它后面非重复出现的数字交换。
3、全排列的非递归就是由后向前找替换数和替换点,然后由后向前找第一个比替换数大的数与替换数交换,最后颠倒替换点后的所有数据。

二、字符串的组合

题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。

上面我们详细讨论了如何用递归的思路求字符串的排列。同样,本题也可以用递归的思路来求字符串的组合。

假设我们想在长度为n的字符串中求m个字符的组合。我们先从头扫描字符串的第一个字符。针对第一个字符,我们有两种选择:第一是把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选取m-1个字符;第二是不把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选择m个字符。这两种选择都很容易用递归实现。下面是这种思路的参考代码:
  1. #include<iostream>  
  2. #include<vector>  
  3. #include<cstring>  
  4. using namespace std; 
  5. #include<assert.h>  
  6.  
  7. void Combination(char *string ,int number,vector<char> &result); 
  8.  
  9. void Combination(char *string) 
  10.     assert(string != NULL); 
  11.     vector<char> result; 
  12.     int i , length = strlen(string); 
  13.     for(i = 1 ; i <= length ; ++i) 
  14.         Combination(string , i ,result); 
  15.  
  16. void Combination(char *string ,int number , vector<char> &result) 
  17.     assert(string != NULL); 
  18.     if(number == 0) 
  19.     { 
  20.         static int num = 1; 
  21.         printf("第%d个组合\t",num++); 
  22.  
  23.         vector<char>::iterator iter = result.begin(); 
  24.         for( ; iter != result.end() ; ++iter) 
  25.             printf("%c",*iter); 
  26.         printf("\n"); 
  27.         return
  28.     } 
  29.     if(*string == '\0'
  30.         return
  31.     result.push_back(*string); 
  32.     Combination(string + 1 , number - 1 , result); 
  33.     result.pop_back(); 
  34.     Combination(string + 1 , number , result); 
  35.  
  36. int main(void
  37.     char str[] = "abc"
  38.     Combination(str); 
  39.     return 0; 
  1. #include<iostream> 
  2. #include<vector> 
  3. #include<cstring> 
  4. using namespace std; 
  5. #include<assert.h> 
  6.  
  7. void Combination(char *string ,int number,vector<char> &result); 
  8.  
  9. void Combination(char *string) 
  10.     assert(string != NULL); 
  11.     vector<char> result; 
  12.     int i , length = strlen(string); 
  13.     for(i = 1 ; i <= length ; ++i) 
  14.         Combination(string , i ,result); 
  15.  
  16. void Combination(char *string ,int number , vector<char> &result) 
  17.     assert(string != NULL); 
  18.     if(number == 0) 
  19.     { 
  20.         static int num = 1; 
  21.         printf("第%d个组合\t",num++); 
  22.  
  23.         vector<char>::iterator iter = result.begin(); 
  24.         for( ; iter != result.end() ; ++iter) 
  25.             printf("%c",*iter); 
  26.         printf("\n"); 
  27.         return
  28.     } 
  29.     if(*string == '\0'
  30.         return
  31.     result.push_back(*string); 
  32.     Combination(string + 1 , number - 1 , result); 
  33.     result.pop_back(); 
  34.     Combination(string + 1 , number , result); 
  35.  
  36. int main(void
  37.     char str[] = "abc"
  38.     Combination(str); 
  39.     return 0; 

由于组合可以是1个字符的组合,2个字符的字符……一直到n个字符的组合,因此在函数void Combination(char* string),我们需要一个for循环。另外,我们一个vector来存放选择放进组合里的字符。

字符串全排列扩展----八皇后问题
    题目:在8×8的国际象棋上摆放八个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。下图中的每个黑色格子表示一个皇后,这就是一种符合条件的摆放方法。请求出总共有多少种摆法。


    这就是有名的八皇后问题。解决这个问题通常需要用递归,而递归对编程能力的要求比较高。因此有不少面试官青睐这个题目,用来考察应聘者的分析复杂问题的能力以及编程的能力。

由于八个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。于是我们可以定义一个数组ColumnIndex[8],数组中第i个数字表示位于第i行的皇后的列号。先把ColumnIndex的八个数字分别用0-7初始化,接下来我们要做的事情就是对数组ColumnIndex做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的八个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==ColumnIndex[i]-Column[j]或者j-i==ColumnIndex[i]-ColumnIndex[j]。

关于排列的详细讨论,详见上面的讲解。
接下来就是写代码了。思路想清楚之后,编码并不是很难的事情。下面是一段参考代码:

  1. #include<iostream>  
  2. using namespace std; 
  3.  
  4. int g_number = 0; 
  5. void Permutation(int * ,int  ,int ); 
  6. void Print(int * ,int ); 
  7.  
  8. void EightQueen( ) 
  9.     const int queens = 8; 
  10.     int ColumnIndex[queens]; 
  11.     for(int i = 0 ; i < queens ; ++i) 
  12.         ColumnIndex[i] = i;    //初始化 
  13.     Permutation(ColumnIndex , queens , 0); 
  14.  
  15. bool Check(int ColumnIndex[] ,int length) 
  16.     int i,j; 
  17.     for(i = 0 ; i < length; ++i) 
  18.     { 
  19.         for(j = i + 1 ; j < length; ++j) 
  20.         { 
  21.             if( i - j == ColumnIndex[i] - ColumnIndex[j] || j - i == ColumnIndex[i] - ColumnIndex[j])  //在正、副对角线上 
  22.                 returnfalse
  23.         } 
  24.     } 
  25.     return true
  26. void Permutation(int ColumnIndex[] ,int length ,int index) 
  27.     if(index == length) 
  28.     { 
  29.         if( Check(ColumnIndex , length) )  //检测棋盘当前的状态是否合法 
  30.         { 
  31.             ++g_number; 
  32.             Print(ColumnIndex , length); 
  33.         } 
  34.     } 
  35.     else 
  36.     { 
  37.         for(int i = index ; i < length; ++i)  //全排列 
  38.         { 
  39.             swap(ColumnIndex[index] , ColumnIndex[i]); 
  40.             Permutation(ColumnIndex , length , index + 1); 
  41.             swap(ColumnIndex[index] , ColumnIndex[i]); 
  42.         } 
  43.     } 
  44.  
  45. void Print(int ColumnIndex[] ,int length) 
  46.     printf("%d\n",g_number); 
  47.     for(int i = 0 ; i < length; ++i) 
  48.         printf("%d ",ColumnIndex[i]); 
  49.     printf("\n"); 
  50.  
  51. int main(void
  52.     EightQueen(); 
  53.     return 0; 

原帖:http://blog.csdn.net/zz198808/article/details/7657168

posted @ 2012-10-21 12:41  唐僧吃肉  阅读(319)  评论(0编辑  收藏  举报