-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31.next-permutation.cpp
More file actions
63 lines (58 loc) · 1.1 KB
/
31.next-permutation.cpp
File metadata and controls
63 lines (58 loc) · 1.1 KB
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
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
using namespace std;
// Not solved :(
// Solved :)
// Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, just reverse nums and done.
// Find the largest index l > k such that nums[l] > nums[k].
// Swap nums[k] and nums[l].
// Reverse the sub-array nums[k + 1:].
class Solution
{
public:
void nextPermutation(vector<int> &nums)
{
int k, n = nums.size(), l;
for (k = nums.size() - 2; k >= 0; --k)
{
if (nums[k] < nums[k + 1])
{
break;
}
}
if (k < 0)
{
reverse(nums.begin(), nums.end());
}
else
{
for (l = n - 1; l > k; --l)
{
if (nums[l] > nums[k])
{
break;
}
}
swap(nums[l], nums[k]);
reverse(nums.begin() + k + 1, nums.end());
}
}
};
void print_array(vector<int> v)
{
for (int i = 0; i < v.size(); i++)
{
if (i > 0)
cout << ", ";
cout << v[i];
}
cout << endl;
}
int main()
{
Solution s;
vector<int> input = {1, 2, 3};
s.nextPermutation(input);
print_array(input);
return 0;
}