leetcode 31. Next Permutation
来源:互联网 发布:linux如何解除软链接 编辑:程序博客网 时间:2024/05/19 08:23
1.题目
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
寻找排列组合的下一个排列。
2.思路
STL上有next_permutation这个函数。原理如下:
在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列了。
class Solution {public: void nextPermutation(vector<int>& nums) { int end = nums.size()-1; int start = 0; if(!end) return; int pos = end; while(nums[pos-1] >= nums[pos--]) { if(pos == start) { reverse(nums.begin(),nums.end()); return;} } int j = end; while(nums[j] <= nums[pos]) j--; swap(nums[j],nums[pos]); reverse(nums.begin()+pos+1,nums.end());}};
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- HTML 5 Video + DOM
- CentOS设置默认启动命令行(不启动图形界面)
- OC 类方法概念
- CS229 Lecture Note(1): Linear Regression
- android:省市二级联动下拉框
- leetcode 31. Next Permutation
- mysql触发器用法详解
- 扩展gcd——poj1061
- Shiro整合SSH开发3:配置Shiro认证后页面地址跳转问题(和详述不配置需要注意的问题)
- SQL语句 保留中文字符以及去掉中文字符
- 【字符串】HDU2137circumgyrate the string
- zigbee网关 cc2530终端裸机驱动超声波测距模块HC-SR04
- 《黑客帝国》里的数字雨
- 智能科普:VR、AR、MR的区别