-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathNext Permutation.cpp
44 lines (28 loc) · 1.07 KB
/
Next Permutation.cpp
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
/*
Solution by Rahul Surana
***********************************************************
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size()==1) return;
int i = nums.size()-2;
while(i >=0 && nums[i]>=nums[i+1]) i--;
if(i < 0){
sort(nums.begin(),nums.end());
return;
}
int j = nums.size()-1;
while(nums[i] >= nums[j]) j--;
cout << i << " "<<j<<"\n";
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
sort(nums.begin()+i+1,nums.end());
}
};