31. Next Permutation
来源:互联网 发布:c#foreach遍历数组 编辑:程序博客网 时间:2024/06/10 22:56
题目
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
寻找当前排列的下一个排列,即所有排列看做数字,下一个排列的值是第一个比当前排列值大的排列,具体算法参考:A simple algorithm from Wikipedia with C++ implementation (can be used in Permutations and Permutations II)
注:可以用sort代替reverse做翻转。
class Solution {public: void nextPermutation(vector<int>& nums) { int k=-1; int size=nums.size(); for(int i=0;i<size-1;++i){//先顺序查找最大的下标k使得nums[k]<nums[k+1] if(nums[i]<nums[i+1]) k=i; } if(k==-1){//如果没有则整体翻转 sort(nums.begin(),nums.end()); return ; } int j=-1; for(int i=size-1;i>k;--i){//找到k之后的最大下标使得nums[k]<nums[j] if(nums[k]<nums[i]){ j=i; break; } } swap(nums[k],nums[j]);//交换后翻转k+1到end的部分 sort(nums.begin()+k+1,nums.end()); }};
阅读全文
0 0
- [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
- 栈与堆的区别
- 腾讯云迁移工具--笔记小结
- oracle通过时间查询
- geoip+php演示样例:通过ip,获取国家名称和代码
- java的(PO,VO,TO,BO,DAO,POJO)类名包名解释
- 31. Next Permutation
- 浅谈android的selector,背景选择器
- SearchView的简单使用
- 阿里云双11云产品访谈 之 互联网中间件
- PHP_notes_01
- cocoa pods 的安装
- redis基本命令
- 读取Excel文档的内容工具类
- SharePoint Online 创建用户和组