forked from dscmsit/Problem-Solving-in-any-Language
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.cpp
More file actions
32 lines (32 loc) · 818 Bytes
/
NextPermutation.cpp
File metadata and controls
32 lines (32 loc) · 818 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
class Solution {
public:
void nextPermutation(vector<int>& nums)
{
int len = nums.size();
// if(len == 1) return;
int idx1, idx2;
for(int i = len-2; i >= 0; i--)
{
if(nums[i] < nums[i+1])
{
idx1 = i; //idx1 = 0
break;
}
}
if(idx1 < 0)
reverse(nums.begin(), nums.end());
else
{
for(int j = len-1; j > idx1; j--)
{
if(nums[j] > nums[idx1])
{
idx2 = j; //idx2 = 2
break;
}
}
swap(nums[idx1],nums[idx2]);
reverse(nums.begin()+(idx1+1), nums.end());
}
}
};