31. Next Permutation
来源:互联网 发布:mac adobe id安装失败 编辑:程序博客网 时间:2024/04/29 08:40
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
next_permutation实现原理
在《STL源码解析》中找到了这个函数,在此也简单叙述一下原理:
在STL中,除了next_permutation外,还有一个函数prev_permutation,两者都是用来计算排列组合的函数。前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。
class Solution {public: void nextPermutation(vector<int>& nums) { int k = -1; for(int i = nums.size()-2;i >= 0; --i){ if(nums[i] < nums[i+1]){ k = i; break; } } if(k == -1){ reverse(nums.begin(), nums.end()); return; } int l = -1; for(int j = nums.size()-1; j > k; --j){ if(nums[k] < nums[j]){ l = j; break; } } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1,nums.end()); }};
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- hadoop2中Mappers和Reducers堆栈的大小配置
- Struts2的OGNL表达式——1
- 史上最全的团队文档协作及管理工具盘点,看看哪款适合你
- win7+vs2013+dlib配置
- JVM源码分析之Java类加载过程
- 31. Next Permutation
- ubuntu12.04的64位系统安装的注意事项
- 判断字符串中每个字符出现的次数
- c::求两个数的最大公约数和最小公倍数
- CSP考试 2016年12月第2题 工资计算 C++实现
- 面试题24:二叉搜索树的后续遍历序列
- 练习
- linux时间相关命令
- Grunt常用插件及示例说明