LeetCode31. Next Permutation
来源:互联网 发布:非诚勿扰网络直播时间 编辑:程序博客网 时间:2024/06/04 21: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
#include<vector>#include<iostream>using namespace std;class Solution {private: void myinverse(vector<int>& nums,int left,int n){ int sum=n+left,j=(sum+1)/2,temp,i=left; while(i<j){ temp=nums[i]; nums[i]=nums[sum-1-i]; nums[sum-1-i]=temp; ++i; } }public: void nextPermutation(vector<int>& nums) { int n=nums.size(); if(n>1){ int i=n-1,j=n-2,temp=0; if(nums[i]>nums[j]){ temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } else{ while(i>0){ if(nums[i]>nums[i-1]){ break; } --i; } if(i==0){ myinverse(nums,0,n); } else if(nums[i-1]<nums[n-1]){ temp=nums[i-1]; nums[i-1]=nums[n-1]; nums[n-1]=temp; myinverse(nums,i,n); } else if(nums[i-1]>=nums[n-1]){ temp=nums[i-1]; int t=i; while(temp<nums[t]){ ++t; } --t; nums[i-1]=nums[t]; nums[t]=temp; nums[t]=temp; myinverse(nums,i,n); } } } }};void main(){ //int a[6]={5,4,7,5,3,2},n=6; int a[6]={4,4,2,3,1,1},n=6; //int a[6]={1,3,6,5,4,2},n=6; //int a[2]={1,1},n=2; vector<int> nums(n); nums.reserve(n); nums.assign(&a[0],&a[n]); cout<<nums[0]<<endl; cout<<nums[1]<<endl; cout<<nums[2]<<endl; cout<<nums[3]<<endl; cout<<nums[4]<<endl; cout<<nums[5]<<endl; Solution So; So.nextPermutation(nums); cout<<nums[0]<<endl; cout<<nums[1]<<endl; cout<<nums[2]<<endl; cout<<nums[3]<<endl; cout<<nums[4]<<endl; cout<<nums[5]<<endl;}
0 0
- [LeetCode31]Next Permutation
- LeetCode31:Next Permutation
- Leetcode31 Next Permutation
- LeetCode31 Next Permutation
- leetcode31:Next Permutation
- leetcode31---Next Permutation
- Leetcode31 Next Permutation
- LeetCode31. Next Permutation
- leetcode31. Next Permutation
- leetcode31~Next Permutation
- LeetCode31. Next Permutation
- Leetcode31. Next Permutation
- leetcode31. Next Permutation
- LeetCode31. Next Permutation
- leetcode31 Next Permutation
- Leetcode31 Next Permutation
- leetcode31. Next Permutation
- LeetCode31. Next Permutation最清晰的解法
- codeforces/contest/797/problem/B
- zhubajiewang面试小结
- 二叉树的所有路径
- Servlet3.0新特性(从注解配置到websocket编程)
- python操作数据库相关的代码
- LeetCode31. Next Permutation
- 基于C语言Win32API的可视化界面的qaac
- POJ 3311 Hie with the Pie Floyd+状压dp
- Android跑Monkey
- 记录自已学习之宏定义
- 二叉树的路径和
- Java结构型设计模式-装饰(二)
- 手机键盘
- 继承