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
解题思路:
从最后一位往前找,找到可以进行调整的数字,调整的时候,在已经搜索
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<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int> &num) {
int start = 0;
int end = num.size()-1;
//遍历寻找可替换元素
for(int i=num.size()-2;i>=0;i--){
if(num[i]<num[i+1]){
int index = i+1;
//找到对应位置
for(int j=i+2;j<num.size();++j)
if(num[j]>num[i])
index = j;
else
break;
int tmp = num[index];
num[index] = num[i];
num[i]= tmp;
//逆序排列,原来是从大到小
start = i+1;
break;
}
}
while(start<end){
int tmp = num[start];
num[start++] = num[end];
num[end--] = tmp;
}
}
};
int main(){
vector<int> vint;
vint.push_back(1);
vint.push_back(3);
vint.push_back(2);
vint.push_back(2);
vint.push_back(1);
Solution s;
s.nextPermutation(vint);
for(int i=0;i<vint.size();++i)
cout<<vint[i]<<" ";
cout<<endl;
return 0;
}