全排列的非递归解法
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:
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; }
相关文章推荐
- 全排列(含递归和非递归的解法)
- 全排列(含递归和非递归的解法)
- c全排列解法(非递归)
- 全排列的递归解法
- 数据结构之栈与递归的应用(全排列递归解法)
- 全排列(含递归和非递归的解法)
- 全排列(含递归和非递归的解法)
- 求数列的全排列(递归解法)
- 面试题12: 打印1到最大的n位数(递归解法,全排列的递归解法)
- 全排列(含递归和非递归的解法)
- 全排列(含递归和非递归的解法)(转)
- 全排列的递归解法
- 全排列的递归和非递归解法
- 递归实现全排列(按字典序)
- [LeetCode]Maximum Depth of Binary Tree(递归和层序遍历解法)@python
- 递归解决全排列生成算法
- 递归的使用案例(数据的全排列)
- 蒜头君吃桃递归解法
- 数据结构之栈与递归的实现及应用(斐波拉契数列递归解法和strlen递归解法)
- 递归程序与全排列问题