-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextPermutation.cpp
More file actions
executable file
·54 lines (47 loc) · 1.49 KB
/
nextPermutation.cpp
File metadata and controls
executable file
·54 lines (47 loc) · 1.49 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
/*
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
*/
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void nextPermutation(vector<int> &num) {
int k = -1;
int p = -1;
// find the largest k such that num[k] < num[k+1]
for(int i = 0; i < num.size()-1; ++i)
if(num[i] < num[i+1])
k = i;
// if k does not exist, this is the last sequence. We return its reverse
if(k < 0) {
reverse(num.begin(),num.end());
return;
}
// find the largest p such that num[p] > num[k]
for(int i = 0; i < num.size(); ++i)
if(num[i] > num[k])
p = i;
// swap them
swap(num[p],num[k]);
// reverse the last part of sequence from k + 1
reverse(num.begin() + k + 1, num.end());
return;
}
int main(int argc, char const *argv[])
{
vector<int> num(4,0);
for(int i = 0; i < 4; i++)
num[i] = i+1;
nextPermutation(num);
for(int i = 0; i < 4; ++i)
cout << num[i] << " ";
cout << endl;
return 0;
}