-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNEXT PERMUTATION .cpp
43 lines (38 loc) · 1.01 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
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
void nextPermutation(vector<int> &nums)
{
int ind = -1;
int n = nums.size();
// step 1 finding the breakpoint
for (int i = n - 2; i >= 0; i--)
{
if (nums[i] < nums[i + 1])
{
ind = i;
break;
}
}
// if there is no break point then
if (ind == -1)
{
reverse(nums.begin(), nums.end());
return;
}
// Step 2 Now after we got the breakpoint from the back to that breakpoint we have to
// find which is least greater
for (int i = n - 1; i > ind; i--)
{
if (nums[i] > nums[ind])
{
swap(nums[i], nums[ind]);
break;
}
}
reverse(nums.begin() + ind + 1, nums.end());
}
};
// LEETCODE PROBLEM - 31