【Leetcode】之Next Permutation
来源:互联网 发布:2016知乎日报启动画面 编辑:程序博客网 时间:2024/05/14 09:37
一.问题描述
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
二.我的解题思路
首先要理解什么叫字典序排列,可参见博客:http://blog.csdn.net/zhutulang/article/details/7763810。
弄清楚什么叫字典序排列之后,这套题目就转换成了常见的数组问题,测试通过的程序如下:
class Solution {public: void nextPermutation(vector<int>& nums) { int len=nums.size(); bool flag=0;int r=0; //从数组的右侧开始寻找第一个nums[r-1]<nums[r]的数 for( r=len-1;r>0;r--){ if(nums[r-1]<nums[r]){ flag=1; break; } } //需要按从小到大的顺序进行排列 if(flag==0){ reverse(nums,0,len-1); } else{ int curr_idx= r-1; int min=nums[curr_idx+1];int min_idx=curr_idx+1; for(int r=curr_idx+1;r<len;r++){ if(nums[r]>nums[curr_idx]){ if(nums[r]<=min){ min=nums[r];min_idx=r; } } } swap(nums[curr_idx],nums[min_idx]); reverse(nums,curr_idx+1,len-1); } }private: void swap(int& a,int& b){ int tmp=0; tmp=b; b=a; a=tmp; } void reverse(vector<int>& nums,int st,int end){ int tmp=0; while(st<=end){ tmp=nums[st]; nums[st]=nums[end]; nums[end]=tmp; st++; end--; } }};
0 0
- LeetCode之Next Permutation
- leetcode之Next Permutation
- LeetCode之Next Permutation
- 【Leetcode】之Next Permutation
- leetcode之八Next Permutation
- Leetcode之Next Permutation (Medium)
- 数组之Next Permutation---leetcode
- Leetcode之Next Permutation 问题
- LeetCode算法题之Next Permutation
- leetcode之路031 Next Permutation
- LeetCode进阶之路(Next Permutation)
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- HTML5定稿一周年 你必须要重新认识HTML5了
- MQTT XMPP HTTP 即时通讯方案对比
- web项目中各种路径的获取
- linux常用命令
- [转]请放下你的无效社交
- 【Leetcode】之Next Permutation
- Mysql
- JAVA基础(1)
- C#事例调用类静态方法
- java 删除文件夹
- 【Java并发编程实战】—–“J.U.C”:ReentrantReadWriteLock
- eclipse project explorer 下面的字体怎么更改大小
- Unity3d 学习01
- ROS新手教程【二】ROS总体框架