Simple C++ solution using swap and sort(378 ms)


#1

vector Solution::nextPermutation(vector &A) {
int n= A.size(); int cnt=0;
for(int i=n-1;i>=1;i–){
if(A[i]<=A[i-1]) continue;
cnt=1; int k=i;
reverse(A.begin()+i,A.end());
while(k<n){
if(A[k]>=A[i-1]) {
break;
}
k++;
}
swap(A[k],A[i-1]);
sort(A.begin()+i,A.end());
break;
}
if(cnt==0) {
reverse(A.begin(),A.end());
}
return A;
}