Leetcode 31 Next Permutation
来源:互联网 发布:mac dare you 不好看 编辑:程序博客网 时间:2024/06/16 22:01
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
找到字典序的下一个排列.
偷懒做法
class Solution {public: void nextPermutation(vector<int>& nums) { if(next_permutation(nums.begin(),nums.end())) return; sort(nums.begin(),nums.end()); }};
当然本着小题大做的原则,肯定不能这样放松要求哇。
算法原理查看 http://blog.csdn.net/accepthjp/article/details/52432954
找出从最右向左最长递增序列的左边一个元素,将最长递增序列逆置,这样得到的是该序列的最小字典序排列,再将找到的左边一个元素和该序列中大于它的最小一个元素交换位置。
class Solution {public: void nextPermutation(vector<int>& nums) { if(nums.size()<2) return ; for(int i=nums.size()-1;i>0;i--) if(nums[i]>nums[i-1]) { reverse(nums.begin()+i,nums.end()); vector<int>::iterator it=upper_bound(nums.begin()+i,nums.end(),nums[i-1]); swap(*it,nums[i-1]); return ; } reverse(nums.begin(),nums.end()); }};
1 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
- 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
- [Lintcode]Container With Most Water
- 嵌入式调试器原理和各类调试器集锦
- label上添加斜线
- Java设计模式之简单工厂模式
- scala进阶30-for的生成器、定义、过滤器
- Leetcode 31 Next Permutation
- B20 十大金句
- 数组形参
- LeetCode 题目总结/分类
- Nim Game——Difficulty:Easy
- Codeforces Round #359 (Div. 2) A
- Android工具类--获取屏幕信息类
- oracle 执行计划学习
- 约瑟夫问题JAVA算法