Next Permutation
https://leetcode.com/problems/next-permutation/
https://www.interviewbit.com/old/problems/next-permutation/
step1> traverse from right to left , a[i] < a[i+1] -->indx1
step2 > traverse from right to left , a[idx2] > a[idx1]
step3 > swap value at idx1 and idx 2
step 4> reverse from idx1+1 to last
class Solution {
public:
void nextPermutation(vector<int>& num) {
int n=num.size(),k,l;
for(k=n-2;k>=0;k--){
if(num[k]<num[k+1]){
break;
}
}
if(k<0){
reverse(num.begin(),num.end());
}
else{
for(l=n-1;l>=k;l--){
if(num[l]>num[k]){
break;
}
}
swap(num[k],num[l]);
reverse(num.begin()+k+1,num.end());
}
}
};
Comments
Post a Comment