您的位置:首页 > 其它

全排列的非递归解法

2013-11-01 12:31 225 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: