全排列的非递归解法


pre:   I  have forgot  where the code comes from . There is a little flaws in the  origin . 


The modified code is as flows:



//#include<algorithm>  
//#include<cstring> 
#include<assert.h>
#include<iostream>  
using namespace std;  
  
  
//[pBegin, pEnd] 之间的字符逆袭
void Reverse(char* pBegin , char* pEnd)  
{  
    while(pBegin < pEnd)  
        swap(*pBegin++ , *pEnd--);  
}  
 //a起初是字母排序的,a每次被改变
bool Next_permutation(char a[])  
{  
    assert(a);  
    char *p , *q , *pFind;  
    char *pEnd = a + strlen(a) - 1;  
    if(a == pEnd)  
        return false;  
    p = pEnd;  
    while(p != a)  
    {  
        q = p;  
        p--;  
        if(*p < *q)  //找降序的相邻2数,前一个数即替换数    
        {  
             //从后向前找比替换点大的第一个数  
            pFind = pEnd;  
            while(*pFind <= *p)  //记得加=,否则对于字符串中有重复字符的情况会陷入死循环
                --pFind;  
            swap(*p , *pFind);  
            //替换点后的数全部反转  
            Reverse(q , pEnd);  
            return true;  
        }  
    }  
    Reverse(a , pEnd);   //如果没有下一个排列,全部反转后返回false     
    return false;  
}  
  
int cmp(const void *a,const void *b)  
{  
    return int(*(char *)a - *(char *)b);  
}  
int main(void)  
{  
    char str[] = "aab";  
    int num = 1;  
    qsort(str , strlen(str),sizeof(char),cmp);  
	puts(str);
    do  
    {  
        printf("第%d个排列\t%s\n",num++,str);   
    }while(Next_permutation(str));  
    return 0;  
}  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值