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<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<ostream>
using namespace std;
void nextPermutation(vector<int> &num) {
vector<int>::reverse_iterator pre_iter;
for (pre_iter = num.rbegin()+1;pre_iter!=num.rend();++pre_iter){
vector<int>::reverse_iterator tmp_iter =pre_iter;
advance(tmp_iter,-1);
if (*pre_iter<*tmp_iter)
break;
}
if (pre_iter==num.rend()){
reverse(num.begin(),num.end());
return;
}
vector<int>::reverse_iterator las_iterator;
for (las_iterator = num.rbegin();las_iterator!=pre_iter;++las_iterator){
if (*las_iterator>*pre_iter)
break;
}
iter_swap(pre_iter,las_iterator);
reverse((pre_iter++).base(),num.end());
}