C++ STL中next_permutation的实现
来源:互联网 发布:win7开机优化加速 编辑:程序博客网 时间:2024/06/06 17:09
next_permutation包含于头文件algorithm中,是经常使用的笔者经常使用的一个函数,在算法竞赛题目中颇为好用,特别是一些猜数字问题,这个函数完全避免了多层循环的问题,使得很多问题不需要自己动脑子一样简单,笔者因此对其实现原理非常感兴趣,查阅相关资料后终于恍然大悟,简单起见,只对整型数组做了测试,详细部分看如下代码,已经写得非常清楚,希望对读者有所帮助。
#include<iostream>#include<algorithm>//包含reverseusing namespace std;bool next_permutation( int* first, int* last ) { if(first == last) return false; //空序列 int* i = first; ++i; if(i == last) return false; //一个元素,没有下一个序列了 i = last; --i; for(;;) { int* ii = i; --i; if(*i < *ii) { //找到第一组连续且满足*i<*ii int* j = last; while(!(*i < *--j)); iter_swap(i, j); reverse(ii, last); return true; } if(i == first) { reverse(first, last); //全逆向,即为最小字典序列,回到起始状态,可以自己体会得到 return false; } } } int main(){ int a[10]={1,2,3,4,5,6,7}; do{ for(int i=0;i<5;i++) cout<<" "<<a[i]; cout<<endl; }while(next_permutation(a,a+5));//为了截屏方便,少量数据测试 return 0;}
运行结果如下,与头文件中该结果一致
0 0
- C++STL的next_permutation
- C++STL的next_permutation
- C++STL的next_permutation
- C++ STL中next_permutation的实现
- 【STL】next_permutation的实现
- C++STL中全排列函数next_permutation的使用
- C++STL中全排列函数next_permutation的使用
- C++STL中全排列函数next_permutation的使用
- 详解STL中next_permutation()函数实现
- C++STL的next_permutation 的用法
- C++ STL next_permutation的实现原理
- C++ STL next_permutation的实现原理
- STL 中 next_permutation 的全排列思路
- HDU 1027 STL中next_permutation的应用
- 九度OJ 1120 全排列 -- 实现C++STL中next_permutation()
- C++中next_permutation的实现
- 使用stl的next_permutation
- STL的next_permutation函数
- Android AIDL尝试
- LeetCode - 5 Longest Palindromic Substring 最长回文子字符串
- 通过Comparator和Comparable对集合进行排序
- New Document
- 关于二维数组当做函数参数的问题
- C++ STL中next_permutation的实现
- MySQL临时表
- 发布webapi 404错误
- 单链表递归反转和非递归翻转
- C语言实现控制行数打印星号金字塔
- java中返回值return的使用
- from now on...
- 深刻的理解Fragment生命周期 都在做什么
- C++本质:类的赋值运算符=的重载,以及深拷贝和浅拷贝