31. Next Permutation
来源:互联网 发布:网络语右友是什么意思 编辑:程序博客网 时间:2024/05/20 20:03
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
算法思想:
对当前排列从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则序列逆序排列,直接逆转序列,算法结束;否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。
#include<iostream>#include<algorithm>#include<vector>using namespace std;class Solution {public: void nextPermutation(vector<int>& nums) { if(nums.size()<2) return; int i; for(i=nums.size()-1;i>0;i--) { if(nums[i]>nums[i-1])//找到一对升序排列的数 break; } if(i==0)//逆序排列直接逆转 reverse(nums.begin(),nums.end()); else { int k; for(k=nums.size()-1;k>i;k--)//在i到nums.end()中寻找第一次比nums[i-1]大的数nums[k] { if(nums[k]>nums[i-1]) break; } swap(nums[i-1],nums[k]);//交换两个数 reverse(nums.begin()+i,nums.end()); } return; }};int main(){ vector<int>number; int i,N,temp; cin>>N; for(i=0;i<N;i++) { cin>>temp; number.push_back(temp); } Solution solve; solve.nextPermutation(number); for(i=0;i<number.size();i++) cout<<number[i]<<' '; cout<<endl; return 0;}
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
- 找零钱的方案数以及所需最少张数的钞票的方案
- 20160902
- 动手实现自己的 STL 容器 《1》---- vector
- Unity3D for VR 学习(2): 暴风魔镜框架探索
- Sublime Text2 CUDA 语法高亮
- 31. Next Permutation
- Eclipse 代码修改后运行还是上次的结果
- 一个js函数中的变量赋值问题
- C/C++程序员应聘常见面试题深入剖析
- yii 各大框架文件上传(文件,视频,音乐)
- Java学习提要——接口进阶
- MACOS brew 安装与卸载
- KODI make
- Android Studio中Module下的gradle文件的基本配置