Skip to content

Commit db443fe

Browse files
committed
Update and rename nextPermutation.cpp to next-permutation.cpp
1 parent 086876e commit db443fe

File tree

2 files changed

+40
-37
lines changed

2 files changed

+40
-37
lines changed

C++/next-permutation.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
void nextPermutation(vector<int> &num) {
7+
nextPermutation(num.begin(), num.end());
8+
}
9+
10+
private:
11+
template<typename BidiIt>
12+
bool nextPermutation(BidiIt begin, BidiIt end) {
13+
const auto rbegin = reverse_iterator<BidiIt>(end);
14+
const auto rend = reverse_iterator<BidiIt>(begin);
15+
16+
// Find the first element (pivot) which is less than its successor.
17+
auto pivot = next(rbegin);
18+
while (pivot != rend && *pivot >= *prev(pivot)) {
19+
++pivot;
20+
}
21+
22+
if (pivot != rend) {
23+
// Find the number which is greater than pivot, and swap it with pivot
24+
auto change = find_if(rbegin, pivot, bind1st(less<int>(), *pivot));
25+
swap(*change, *pivot);
26+
}
27+
28+
// Make the sequence after pivot non-descending
29+
reverse(rbegin, pivot);
30+
31+
return true;
32+
}
33+
};
34+
35+
class Solution2 {
36+
public:
37+
void nextPermutation(vector<int> &num) {
38+
next_permutation(num.begin(), num.end());
39+
}
40+
};

C++/nextPermutation.cpp

Lines changed: 0 additions & 37 deletions
This file was deleted.

0 commit comments

Comments
 (0)