STL经典算法集锦之排列(next_permutation/prev_permutation
来源:互联网 发布:通达信布林线公式源码 编辑:程序博客网 时间:2024/05/20 17:07
STL经典算法集锦之排列(next_permutation/prev_permutation)
STL中涉及到数组的排列的有两个函数,即next_permutation/prev_permutation,分别用于求上一个以及下一个排列。两函数的算法使用的原理大体相同。以next_permutation为例,列出算法并解释。
算法:
首先,从最为段开始往前寻找两个相邻的元素,令第一个元素索引为endi第二个元素索引为endii,且满足array[endi]<array[endii]。然后,再从最尾端开始向前检测,找到第一个大于array[endi]的元素,令其为索引j。将元素array[endi],array[j]对调,然后将endii之后的所有元素颠倒排列。即求的下一个排列。
解释:
一、如果数组k以后的是一个递减序列,则仅依靠调换k以后的元素不可能完成任务,所以必须找到满足k>k+1的元素,即保证k以后的序列不递减。
二、满足一之后,那么下一个序列的第k位一定是从后面找到刚好比a[k]大的一个比a[k]大的一个数打头的(为了保证刚好大于,又k+1之后的元素递减,所以从数组尾开始找到第一个比a[k]大的元素即可满足要求)。将这个数的索引记为j。
三、将a[j]与a[k]对调。此时,j后面的元素是降序的。所以需要把j后面的逆转一下,从降序到升序,如此就得到了恰好比之前序列大一号的序列。
代码:next_permutation
bool nextPermutation(int array[],int len){int endi=len-1;int endii;if(len==1)return false;while(true){endii=endi;endi--;if(array[endi]<array[endii])// 如果前一个元素小于后一个元素{int j=len;while(array[--j]<array[endi]);// 由尾端往前找,直到遇上比array[endi]大的元素swap(array[j],array[endi]); // 交换找到的元素reverse(array+endii,array+len-1);// 将 endii 之后的元素全部逆向重排return true;}if(endi==0)//排列已至最大,无下一个排列{reverse(array,array+len-1);return false;}}}代码:prev_permutation
bool prevPermutation(int array[],int len){int endi=len-1;int endii;if(len==1)return false;while(true){endii=endi;endi--;if(array[endi]>array[endii])// 如果前一个元素大于后一个元素{int j=len;while(array[--j]>array[endi]);// 由尾端往前找,直到遇上比array[endi]小的元素swap(array[j],array[endi]); // 交换找到的元素reverse(array+endii,array+len-1);// 将 endii 之后的元素全部逆向重排return true;}if(endi==0)//排列已至最小,无上一个排列{reverse(array,array+len-1);return false;}}}
- STL经典算法集锦<六>之排列(next_permutation/prev_permutation)
- STL经典算法集锦之排列(next_permutation/prev_permutation
- 【经典算法】STL之next_permutation和prev_permutation
- STL全排列算法next_permutation和prev_permutation
- STL之生成全排列:next_permutation & prev_permutation
- STL算法之 next_permutation、prev_permutation 的原理和实现
- STL_算法_排列(prev_permutation、next_permutation)
- STL源码学习----next_permutation和prev_permutation算法
- STL algorithm算法next_permutation,prev_permutation(39)
- STL算法:prev_permutation和next_permutation的使用
- STL算法:prev_permutation和next_permutation的使用
- STL源码剖析之next_permutation,prev_permutation
- STL具体操作之next_permutation和prev_permutation函数
- STL之next_permutation和prev_permutation函数
- STL prev_permutation&next_permutation
- STL next_permutation and prev_permutation
- STL全排列函数 next_permutation prev_permutation 及拓展
- stl全排列next_permutation()与prev_permutation()函数用法
- Mac OS X 过往12年的演变史
- winsock
- SSE intrinsic函数_优化
- seandroid对selinux的改进
- Java中一个简单易用的JAD 反编译工具
- STL经典算法集锦之排列(next_permutation/prev_permutation
- ubuntu12.04 安装chromium
- 关于System.out.println
- Why are destructors not virtual by default?
- 黑马程序员----JAVA----基础小结----
- 在Openssl 0.9.7c 下找不到 SHA512 算法
- Dalvik虚拟机即时编译系统在unicore上的移植
- MATLAB——scatter的简单应用
- SEQ ACK