-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.cpp
More file actions
34 lines (34 loc) · 821 Bytes
/
Copy pathNext Permutation.cpp
File metadata and controls
34 lines (34 loc) · 821 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:
// Return true if permutate successfully.
bool nextPermutation(vector<int>& num, int start) {
if (start == num.size())
return false;
if (nextPermutation(num, start + 1))
return true;
int i;
for (i = num.size() - 1; i > start; i--) {
if (num[i] > num[start]) {
swap(num[i], num[start]);
int left = start + 1, right = num.size() - 1;
while (left < right) {
swap(num[left], num[right]);
left++;
right--;
}
break;
}
}
return i != start;
}
void nextPermutation(vector<int>& num) {
if (nextPermutation(num, 0))
return;
int left = 0, right = num.size() - 1;
while (left < right) {
swap(num[left], num[right]);
left++;
right--;
}
}
};