Search backwards: when we find the first decending pair of adjacent elements (i.e. num[i-1]<num[i]), swap num[i-1] with the smallest elements after it which is greater than it (num[i-1] ), then sort the elements after index i-1 in ascending order.
class Solution {
public:
void nextPermutation(vector<int> &num) {
if(num.size()<=1) return;
int i;
for(i=num.size()-1;i>=1;i--)
if (num[i]>num[i-1])
break;
if (i==0)
sort(num.begin(),num.end());
else {
int min_greater = i;
for(int j=i;j<num.size();j++)
if(num[j]>num[i-1] && num[j]<num[min_greater])
min_greater = j;
// Swap the element num[i-1] with the smallest-greater element after it
int tmp=num[i-1];
num[i-1]=num[min_greater];
num[min_greater]=tmp;
sort(num.begin()+i,num.end());
}
}
};