字符串全排列

前些天写过一篇关于书中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~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值