Next Permutation
来源:互联网 发布:2016健康大数据 编辑:程序博客网 时间:2024/04/24 14:55
Next PermutationFeb 25 '12
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,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
计算下一个排列的算法:
1. 从当前序列最尾端开始往前寻找两个相邻元素,令前面一个元素为*i,后一个元素为*ii,且满足*i<*ii;
2. 再次从当前序列末端开始向前扫描,找出第一个大于*i的元素,令为*j(j可能等于ii),将i,j元素对调;
3. 将ii之后(含ii)的所有元素颠倒次序,这样所得的排列即为当前序列的下一个排列。
class Solution {public: void nextPermutation(vector<int> &num) { int i = 0; int k = num.size(); while(k-->=1) { if(num[k] > num[k-1]) { i = k; break; } } int j= i-1; k = num.size(); while(k-- != i-1) { if(num[k] > num[i-1]) { j = k; break; } } swap(num[i-1],num[j]); reverse(num.begin()+i,num.end()); }};
60 milli secs
- 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
- Database Architect(数据库架构师)
- 数字和量词相关
- Creating a Customer at the time of creating a Sales Order
- C# Socket编程(3)编码和解码
- 一个免费的Javascript&html5 Charts
- Next Permutation
- python取系统主机名和IP地址以及过滤网卡信息等
- 修复完浏览器后每次打开ie8都会自动弹出管理加载项,请问怎样才能不弹出
- QpushButton 去除外侧的黑色边框
- 机架服务器 远程电源管理 备忘
- openstack 数据库实例删除脚本
- 在linux下设置开机自动启动程序的方法
- C# Socket编程(4)初识Socket和数据流
- Google code jam: Problem A. Minimum Scalar Product