-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.cpp
More file actions
34 lines (32 loc) · 819 Bytes
/
Next Permutation.cpp
File metadata and controls
34 lines (32 loc) · 819 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
33
34
class Solution {
public:
void nextPermutation(vector<int> &num) {
const int len = num.size();
int pos = -1;
for (int i = len - 2; i >= 0; --i) {
if (num[i] < num[i + 1]) {
pos = i;
break;
}
}
if (pos != -1)
for (int i = len - 1; i > pos; --i)
if (num[i] > num[pos]) {
swap(num[i], num[pos]);
break;
}
reverse(num, pos + 1, len - 1);
}
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void reverse(vector<int> &num, int begin, int end) {
while (begin < end) {
swap(num[begin], num[end]);
++begin;
--end;
}
}
};