Next Permutation
来源:互联网 发布:软件系统可靠性分析 编辑:程序博客网 时间:2024/05/20 06:27
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).The replacement must be in-place, do not allocate extra memory.Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1
1.从后往前找到第一个正序对,记录正序对的第一个元素的下标为iMax
2.从后往前找到第一个大于num[iMax]的元素,下标记为jMax
3.交换num[iMax]与num[jMax]
4.将num[iMax]之后的元素翻转
5.将整个num翻转,得到最后结果
class Solution {public: void nextPermutation(vector<int> &num) { int iMax = -1; for(int i = num.size() - 1;i >= 1;i--) if(num[i-1] < num[i]) { iMax = i-1; break; } int jMax = -1; for(int j = num.size() -1 ;j >= iMax;j--) if(num[iMax] < num[j]) { jMax = j; break; } if(iMax != -1 and jMax != -1) { swap(num[iMax],num[jMax]); reverse(num.begin()+iMax+1,num.end()); } else reverse(num.begin(),num.end()); }};
0 0
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- tomcat重启脚本
- Eclipse中如何快速查看jar包中 的class源码
- 什么才算是真正的编程能力?
- live555 源代码简单分析1:主程序
- 九度OJ-题目1522:包含min函数的栈
- Next Permutation
- java 数据格式相互转换
- 事件分发,事件拦截,事件消费
- SQL Server 数据库迁移偏方
- 有趣的python range()函数
- R语言内存管理
- 日经春秋 20150608
- JTAG与SWD的区别
- Spring mvc实现文件上传及html5实现上传进度条