字符串全排列问题

字符串排列与组合算法详解
本文详细介绍了如何使用递归和非递归方法求解字符串的全排列与组合问题,包括处理重复字符的情况,以及利用位运算实现组合的快速生成。

原文链接:http://blog.youkuaiyun.com/zhaojinjia/article/details/9320475


问题:输入一字符串(要求不存在重复字符),打印出该字符串中字符中字符的所有排列。

例如:输入"abc",输出结果为abc, acb, bac, bca, cab和cba。

方法一:比较笨,用一个整型数组,记录当前排列的下标,然后输出下标对应的字符串,空间代价为O(n)

 代码:

  1. //参数:字符串,记录当前全排列组合的字符在字符串中的下标,字符串长度,当前要确定的字符  
  2. void Permutation(char* letter, int* record, int length, int nCur)  
  3. {  
  4.     if ( nCur == length )  
  5.     {  
  6.         static int count = 0;  
  7.         count++;  
  8.         cout << count << "->:\t ";  
  9.         for ( int i = 0; i < length; i++ )  
  10.         {  
  11.             cout << letter[record[i]];  
  12.         }  
  13.         cout << endl;  
  14.         return;  
  15.     }  
  16.   
  17.     for ( int i = 0; i < length; i++ )  
  18.     {  
  19.         //确定当前结点的字符是什么,不能和已经确定的字符相同  
  20.         int j;  
  21.         for ( j = 0; j < nCur; j++ )  
  22.         {  
  23.             if ( i==record[j] )  
  24.                 break;  
  25.         }  
  26.         if ( j != nCur )  
  27.             continue;  
  28.           
  29.         //确定当前字符  
  30.         if ( j == nCur )  
  31.             record[nCur] = i;  
  32.   
  33.         Permutation(letter,record,length,nCur+1);  
  34.     }  
  35. }  

  1. int _tmain(int argc, _TCHAR* argv[])  
  2. {  
  3.     char* letter = "abc";  
  4.     int length = strlen(letter);  
  5.   
  6.     int* record = new int[length];  
  7.       
  8.     Permutation(letter,record,length,0);  
  9.     return 0;  
  10. }  

方法二:

通过找规律,求字符串的全排列,可以看出三步

首先,求所有可能出现在第一个位置的字符,

其次,把第一个字符和其后面的字符一一交换。如下图所示,分别把第一个字符a和后面的b、c等字符交换的情形。

接着,固定第一个字符,求后面所有字符的排列。这个时候我们仍把后面的所有字符分成两部分:后面字符的第一个字符,以及这个字符之后的所有字符。然后把第一个字符逐一和它后面的字符交换

代码:

  1. void Permutation_o(char* pStr, char* pBegin)  
  2. {  
  3.     if (*pBegin == '\0' )  
  4.         cout << pStr <<endl;  
  5.     else  
  6.     {  
  7.         for (char* pCh = pBegin; *pCh!='\0'; pCh++)  
  8.         {  
  9.             char temp = *pCh;  
  10.             *pCh = *pBegin;  
  11.             *pBegin = temp;  
  12.   
  13.             Permutation_o(pStr, pBegin+1);  
  14.   
  15.             temp = *pCh;  
  16.             *pCh = *pBegin;  
  17.             *pBegin = temp;  
  18.         }  
  19.     }  
  20. }  
  21.   
  22. void Permutation_o(char* pStr)  
  23. {  
  24.     if (pStr==NULL)  
  25.         return;  
  26.     Permutation_o(pStr,pStr);  
  27. }  
  28.   
  29. int main(void)  
  30. {  
  31.     char str[10] ;  
  32.     cout <<"input the string: ";  
  33.     cin>> str;  
  34.     cout <<"the string's permutation lists:"<<endl;  
  35.     Permutation_o(str);   
  36.     return 0;  
  37. }  

 

方法三:

由于,我们担心递归的高效性,很多把递归算法改写成非递归算法。但是比较难,但是STL中有一个函数next_permutation(),它的作用是如果对于一个序列,存在按照字典排序后这个排列的下一个排列,那么就返回ture,并且产生这个排列,否则返回false。注意,为了产生这个全排列,这个序列必须是有序的,即调用一次sort函数。

代码:

  1. #include "stdafx.h"  
  2. #include <algorithm>  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. void Permutation(char* pStr, int length)  
  7. {  
  8.     sort(pStr,pStr+length);  
  9.      
  10.     do   
  11.     {  
  12.         cout << pStr <<endl;  
  13.     } while ( next_permutation(pStr,pStr+length) );  
  14. }  
  15.   
  16. int _tmain(int argc, _TCHAR* argv[])  
  17. {  
  18.     char str[10];  
  19.     cout << "Input the string:";  
  20.     cin >> str;  
  21.     int lengh = strlen(str);  
  22.     cout << "Permutation is :"<<endl;  
  23.       
  24.     Permutation(str,lengh);  
  25.     return 0;  
  26. }  


 

问题:输入一字符串(要求可以存在重复字符),打印出该字符串中字符的所有排列。

例如:输入"abb",输出结果为abb, bab, bba。

方法一:

思路:在上面的代码基础之上稍加修改即可。我们可以用一个hash记录已经存在的全排列。防止重复输出。

代码:

  1. void Permutation_o(char* pStr, char* pBegin, map<string, string>& Dinstinct)  
  2. {  
  3.     if (*pBegin == '\0' )  
  4.     {  
  5.         map <string, string> :: const_iterator iter;  
  6.         string strString(pStr);  
  7.   
  8.         if ( Dinstinct.find(strString) == Dinstinct.end() ) //不存在  
  9.         {  
  10.             cout << pStr <<endl;  
  11.             Dinstinct.insert(pair<string, string>(strString,strString));  
  12.         }  
  13.     }  
  14.     else  
  15.     {  
  16.         for (char* pCh = pBegin; *pCh!='\0'; pCh++)  
  17.         {  
  18.             char temp = *pCh;  
  19.             *pCh = *pBegin;  
  20.             *pBegin = temp;  
  21.   
  22.             Permutation_o(pStr, pBegin+1, Dinstinct);  
  23.   
  24.             temp = *pCh;  
  25.             *pCh = *pBegin;  
  26.             *pBegin = temp;  
  27.         }  
  28.     }  
  29. }  
  30.   
  31. void Permutation_o(char* pStr)  
  32. {  
  33.     if (pStr==NULL)  
  34.         return;  
  35.   
  36.     map<string, string> Dinstinct;  
  37.     Permutation_o(pStr,pStr,Dinstinct);  
  38. }  
  39.   
  40. int main(void)  
  41. {  
  42.     char str[10] ;  
  43.     cout <<"input the string: ";  
  44.     cin>> str;  
  45.     cout <<"the string's permutation lists:"<<endl;  
  46.     Permutation_o(str);  
  47.     return 0;  
  48. }  

 

方法二:

思路:去重的全排列就是从第一个数字起每个数分别与它后面非重复出现的数字交换。

例如:“abb”,第一个字符a和第二个字符b交换,得到“bab”,此时由于第二个字符和第三个字符相同,所有第一个字符“a”不与第三个字符“b“交换。再考虑,”bab“,第二个字符和第三个字符不同,交换得”bba“,此时结束。生成全部排列

代码:

  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. //在[nBegin,nEnd)区间中是否有字符与下标为pEnd的字符相等    
  6. bool IsSwap(char* pBegin, char* pEnd)  
  7. {  
  8.     char* p;  
  9.     for (p=pBegin; p<pEnd; p++)  
  10.     {  
  11.         if (*p == *pEnd)  
  12.             return false;  
  13.     }  
  14.     return true;  
  15. }  
  16.   
  17. void Permutation(char* pStr, char* pBegin)  
  18. {  
  19.     if (*pBegin == '\0')  
  20.         cout << pStr <<endl;  
  21.     else  
  22.     {  
  23.         for (char* pCh = pBegin; *pCh!='\0'; pCh++)  
  24.         {  
  25.             if( IsSwap(pBegin,pCh) )  
  26.             {  
  27.                 char temp = *pCh;    
  28.                 *pCh = *pBegin;    
  29.                 *pBegin = temp;    
  30.   
  31.                 Permutation(pStr, pBegin+1);    
  32.   
  33.                 temp = *pCh;    
  34.                 *pCh = *pBegin;    
  35.                 *pBegin = temp;    
  36.             }  
  37.         }  
  38.     }  
  39. }  
  40.   
  41. void Permutation(char* pStr)  
  42. {  
  43.     if (pStr==NULL)  
  44.         return;  
  45.     Permutation(pStr,pStr);  
  46. }  
  47.   
  48. int _tmain(int argc, _TCHAR* argv[])  
  49. {  
  50.     char str[10];  
  51.     cout << "Input the string:";  
  52.     cin >> str;  
  53.     cout << "Permutation is :"<<endl;  
  54.       
  55.     Permutation(str);  
  56.     return 0;  
  57. }  

方法三:

与上一问题的方法三,代码完全一样,调用STL中的next_permutation函数,可以实现。

方法四:自己用非递归实现,基于STL中next_permutation函数思想

     要考虑全排列的非递归实现,先来考虑如何计算字符串的下一个排列。如"1234"的下一个排列就是"1243"。只要对字符串反复求出下一个排列,全排列的也就迎刃而解了。

基本思想是:
1.对初始队列进行排序,找到所有排列中最小的一个排列Pmin。
2.找到刚刚好比Pmin大比其它都小的排列P(min+1)。
3.循环执行第二步,直到找到一个最大的排列,算法结束。
如排列ABCDE,这是所有排列中最小的一个排列,刚好比ABCDE大的排列是:ABCED。

算法如下:
给定已知序列P = A1A2A3.....An
对P按字典排序,得到P的一个最小排列Pmin = A1A2A3....An ,满足Ai > A(i-1) (1 < i <= n)
从Pmin开始,找到刚好比Pmin大的一个排列P(min+1),再找到刚好比P(min+1)大的一个排列,如此重复。
1.从后向前(即从An->A1),找到第一对为升序的相邻元素,即Ai < A(i+1)。
若找不到这样的Ai,说明已经找到最后一个全排列,可以返回了。
2.从后向前,找到第一个比Ai大的数Aj,交换Ai和Aj。
3.将排列中A(i+1)A(i+2)....An这个序列的数逆序倒置,即An.....A(i+2)A(i+1)。因为由前面第1、2可以得知,A(i+1)>=A(i+2)>=.....>=An,这为一个升序序列,应将该序列逆序倒置,所得到的新排列才刚刚好比上个排列大。
4.重复步骤1-3,直到返回。

代码:

  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. //两字符交换  
  6. void Swap(char*a, char* b)  
  7. {  
  8.     char t = *a;  
  9.     *a = *b;  
  10.     *b = t;  
  11. }  
  12.   
  13. //反转区间  
  14. void Reverse(char* a, char* b)  
  15. {  
  16.     while ( a < b)  
  17.         Swap(a++,b--);  
  18. }  
  19.   
  20. //下一个排列  
  21. bool Next_Permutation(char* a)  
  22. {  
  23.     char *pEnd = a + strlen(a);  
  24.     if (a==pEnd)  
  25.         return false;  
  26.     char *p,*q,*pFind;  
  27.     pEnd--;  
  28.     p = pEnd;  
  29.     while ( p != a )  
  30.     {  
  31.         q = p;  
  32.         --p;  
  33.         if (*p < *q) //找降序的相邻2数,前一个数即替换数  
  34.         {  
  35.             //从后向前找比替换点大的第一个数  
  36.             pFind = pEnd;  
  37.             while (*pFind<=*p)  
  38.                 --pFind;  
  39.             //替换  
  40.             Swap(pFind,p);  
  41.             //替换点后的数全部反转  
  42.             Reverse(q, pEnd);  
  43.             return true;  
  44.         }  
  45.     }  
  46.     Reverse(p, pEnd);   //如果没有下一个排列,全部反转后返回true  
  47.     return false;  
  48. }  
  49.   
  50. int QsortCmp(const void *pa, const void *pb)  
  51. {  
  52.     return *(char*)pa - *(char*)pb;  
  53. }  
  54.   
  55. int _tmain(int argc, _TCHAR* argv[])  
  56. {  
  57.     char str[10];  
  58.     cout << "Input the string:";  
  59.     cin >> str;  
  60.     int lengh = strlen(str);  
  61.     qsort(str,lengh, sizeof(char), QsortCmp);  
  62.     cout << "Permutation is :"<<endl;  
  63.       
  64.     do   
  65.     {  
  66.         cout << str <<endl;  
  67.     } while (Next_Permutation(str));  
  68.     return 0;  
  69. }  

 

问题:输入一个字符串(要求不存在重复字符),输出该字符串中字符的所有组合。

例如:如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。

方法一:

思路:同样是用递归求解。可以考虑求长度为n的字符串中m个字符的组合,设为C(n,m)。原问题的解即为C(n, 1), C(n, 2),...C(n, n)的总和。对于求C(n, m),从第一个字符开始扫描,每个字符有两种情况,要么被选中,要么不被选中,如果被选中,递归求解C(n-1, m-1)。如果未被选中,递归求解C(n-1, m)。不管哪种方式,n的值都会减少,递归的终止条件n=0或m=0。

代码:

  1. #include "stdafx.h"  
  2. #include <vector>  
  3. #include <string>  
  4. #include <iostream>  
  5. using namespace std;  
  6.   
  7. /* 
  8.     函数功能:从一个字符串中选m个元素 
  9.     函数参数:pStr为字符串,m为选的元素个数,result为选中的 
  10.     无返回值。*/  
  11. void Combination_m(char* pStr, int m, vector<char> &result)  
  12. {  
  13.     //字符串为空,或者长度达不到m  
  14.     if ( pStr==NULL || (*pStr=='\0'&&m!=0) )  
  15.         return;  
  16.     //出口,输出组合  
  17.     if (m==0)  
  18.     {  
  19.         for ( unsigned i = 0; i < result.size(); i++ )  
  20.             cout << result[i];  
  21.           
  22.         cout << endl;  
  23.         return;  
  24.     }  
  25.   
  26.     //如果长度没有达到m  
  27.       
  28.     //此时选择这个元素  
  29.     result.push_back(*pStr);  
  30.     Combination_m(pStr+1, m-1, result);  
  31.     result.pop_back();  
  32.   
  33.     //不选择这个元素  
  34.     Combination_m(pStr+1, m, result);  
  35. }  
  36.   
  37. /* 
  38.     函数功能:求一个字符串的组合 
  39.     函数参数:pStr为字符串 
  40.     无返回值*/  
  41. void Combination(char* pStr)  
  42. {  
  43.     if ( pStr==NULL || *pStr=='\0' )  
  44.         return;  
  45.     int number = strlen(pStr);  
  46.       
  47.     for ( int i = 1; i <= number; i++ )  
  48.     {  
  49.         vector<char> result;  
  50.         Combination_m(pStr, i, result);  
  51.     }  
  52. }  
  53.   
  54.   
  55. int _tmain(int argc, _TCHAR* argv[])  
  56. {  
  57.     char* a="abc";  
  58.     cout << "string a's combination: "<<endl;  
  59.     Combination(a);  
  60.   
  61.     cout << "string b's combination: "<<endl;  
  62.     char* b="abb";  
  63.     Combination(b);  
  64.   
  65.     system("pause");  
  66.     return 0;  
  67. }  

结果如下:


我们看到,对于有相同字符的字符串,求得的全排列有问题,没去重复的。

方法二:利用位运算来实现求组合

例如:对于字符序列“abc”,让其与1-7的二进制相与,每次输出对应二进制为1的那几位,即可输出全部组合。

代码:

  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5.   
  6. void print_subset(char* pStr, int n , int s)    
  7. {    
  8.     for(int i = 0 ; i < n ; ++i)    
  9.     {    
  10.         if( s & (1<<i) )         // 判断s的二进制中哪些位为1,即代表取某一位    
  11.             cout << pStr[i] <<" ";  
  12.     }    
  13.     cout <<endl;  
  14. }    
  15.   
  16. void subset(char* pStr, int n)    
  17. {    
  18.     for(int i= 1 ; i < (1<<n) ; ++i)    
  19.     {    
  20.         print_subset(pStr,n,i);    
  21.     }    
  22. }    
  23.   
  24. int main(void)    
  25. {    
  26.     char Str[10];  
  27.     cout<<"Input the string:";  
  28.     cin>> Str;  
  29.     cout<<"----------"<<endl;  
  30.   
  31.     subset(Str,strlen(Str));    
  32.     return 0;    
  33. }    


 

问题:输入一个字符串(要求可以存在重复字符),输出该字符串中字符的所有组合。

思路:记录每个组合中每个字符出现的次数,防止下次输出

代码略。

如果有什么好思路,请留言,谢谢交流。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值