-
Notifications
You must be signed in to change notification settings - Fork 0
/
nextPermutation.cpp
53 lines (45 loc) · 1.23 KB
/
nextPermutation.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
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
using namespace std;
void nextPermutation(vector<int>& num);
void swap(vector<int>& num, int i, int j);
void reverse(vector<int>& num, int s);
void nextPermutation(vector<int>& num) {
/* code */
if(num.empty() || num.size() == 0) return;
for(int i = num.size() - 2; i >= 0; i++) {
if(num[i] < num[i+1]) {
int j=num.size() -1;
for(; j > i; j--) if(num[j] > num[i]) break;
swap(num, i, j);
reverse(num, i + 1);
return;
}
}
reverse(num, 0);
return;
}
void swap(vector<int>& num, int i, int j){
int t = num[i];
num[i] = num[j];
num[j] = t;
}
void reverse(vector<int>& num, int s){
int e = num.size() - 1;
while(s < e) {
swap(num, s, e);
s++;
e--;
}
}
int main(){
int test[5] = {1, 2, 3, 4, 5};
vector<int> num;
num.assign(test, test + 5);
nextPermutation(num);
for(int i = 0; i < num.size(); i++){
cout << num[i] << " ";
}
cout << endl;
return 0;
}