# [leetcode] Next Permutation

### Next Permutation

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`

tag:array

```class Solution {
public:
void nextPermutation(vector<int> &num) {
int size = num.size();
if(size <= 1){
return;
}
vector<int>::iterator maxV = num.end() - 1;
for(vector<int>::iterator it = num.end() - 1 ; it >= num.begin(); it--){
if(*it < *maxV){
vector<int>::iterator itLarger = maxV;
for(vector<int>::iterator itp = it; itp != num.end(); itp++){
if(*itp > *it && *itp < *itLarger){
itLarger = itp;
}
}
int tmp = *it;
*it = *itLarger;
*itLarger = tmp;
sort((it+1), num.end());
return;
}
else{
maxV = it;
}
}
//no nexPermutation found, reorder to the smallest permutation
sort(num.begin(), num.end());
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.