-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextPermutation.cpp
More file actions
39 lines (37 loc) · 855 Bytes
/
nextPermutation.cpp
File metadata and controls
39 lines (37 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> nextPermutation(vector<int> nums){
int n=nums.size();
int index=-1;
for(int i=n-2; i>=0; i--){
if(nums[i]<nums[i+1]){
index=i;
break;
}
}
if(index==-1){
reverse(nums.begin(), nums.end());
return nums;
}
for(int i=n-1; i>=index; i--){
if(nums[i]>nums[index]){
swap(nums[i], nums[index]);
break;
}
}
reverse(nums.begin()+index+1, nums.end());
return nums;
}
int main(){
vector<int> nums={1, 2, 3, 4, 5, 6};
vector<int> result=nextPermutation(nums);
cout<<"Next greater permutation will be : ";
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}