forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Next_Permutation.cc
32 lines (32 loc) · 947 Bytes
/
Next_Permutation.cc
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
class Solution {
public:
void reverse(vector<int> &num, int st, int ed) {
while (st < ed) {
swap(num[st], num[ed]);
st++, ed--;
}
}
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (num.size() <= 1) {
return;
}
int left, right;
bool flag = false;
for (left = num.size() - 2; !flag && left >= 0; left--) {
for (right = num.size() - 1; right > left; right--) {
if (num[left] < num[right]) {
flag = true;
swap(num[left], num[right]);
break;
}
}
}
if (flag) {
reverse(num, left + 2, num.size() - 1);
} else {
reverse(num, 0, num.size() - 1);
}
}
};