-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext_permutation.cpp
More file actions
54 lines (44 loc) · 982 Bytes
/
Copy pathnext_permutation.cpp
File metadata and controls
54 lines (44 loc) · 982 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
void nextPermutation(vector<int>& nums) {
int k = nums.size()-1 ;
if( k <= 0)
return;
int i = k;
while( i > 0 && nums[i-1] > nums[i] ){
i--;
}
if( i == 0){
reverse(nums.begin(), nums.end());
return;
}
while(i <= k){
if( i == k){
swap(nums[i],nums[i-1]);
break;
}
if( nums[k] <= nums[i-1] ){
if( nums[k-1] > nums[i-1]){
swap(nums[i-1],nums[k-1]);
break;
}
}else{
swap(nums[i-1],nums[k]);
break;
}
k--;
}
sort(nums.begin() + i, nums.begin() + nums.size());
}
int main(int argc, char const *argv[])
{
vector<int> arr = {1,3,2};
nextPermutation(arr);
cout<<"[";
for (size_t i = 0; i < arr.size(); i++)
{
cout<<arr[i]<<",";
}
cout<<"]\n";
return 0;
}