前些天写过一篇关于书中bug的文章,但是显然对不起题目中的一二两字,所以在此补充一下。当时确实打算写两例的,但是后来发现时我自己错了,所以呢,还要告诫自己,要反复论证哈~
今天这个问题源自何海涛老师的《剑指offer》,其中有一个问题是打印出输入字符串的全排列的,这个问题在王晓东老师的《算法设计与分析》中第一章也有讲,就是用递归地方法,不断地将当前串的首字符与其他字符进行交换,我们看下代码吧
void Permutation(char* pStr)
{
if(pStr == NULL)
return;
Permutation(pStr, pStr);
}
void Permutation(char* pStr, char* pBegin)
{
if(*pBegin == '\0')
{
printf("%s\n", pStr);
}
else
{
for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)
{
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
Permutation(pStr, pBegin + 1);
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}
当你输入不含重复字符的字串时,不会有任何问题的,但是之前自己看了今年阿里的笔试题,有一题是这样子说的,问“alibaba”的字符全排列共有多少种,哈,答案应该是多少,我就不说了吧,重点是上面的代码遇到这种输入时输出的结果是A(n,n)个,这样子应该是不可以的吧
我们可以给每层递归函数设置一个string或char型数组来记录已经在当前串首位置出现的字符,如果*pCh已经出现过一次,pCh+1就好了,因为C++的string用起来比较方便,所以用string好了
</pre><pre name="code" class="cpp">#include<cstdio>
#include<memory>
#include<string>
using namespace std;
void Permutation(char* pStr, char* pBegin,int& count);
void Permutation(char* pStr, int& count)
{
if(pStr == NULL)
return;
Permutation(pStr, pStr,count);
}
void Permutation(char* pStr, char* pBegin,int &count)
{
if(*pBegin == '\0')
{
printf("%s\n", pStr);
count++;
}
else
{
string s="";
for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)
{
if(s.find(*pCh)!=-1)
continue;
s+=*pCh;
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
Permutation(pStr, pBegin + 1,count);
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}
int main()
{
char str[1024]="";
int count=0;
while(scanf("%s",str)!=EOF)
{
Permutation(str,count);
memset(str,0,sizeof(str));
printf("%d\n",count);
count=0;
}
return 0;
}
这个方法虽然不怎么高明,不过目前只想到这儿了
另外,我又加了一个int& count参数记录排列的个数,这样子验证一下我们的“alibaba”对不对
alibaba太多了,我们看看最后的结果吧
OK~