-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextPermutation.cpp
48 lines (45 loc) · 1.09 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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void reverse(vector<int>& arr, int start, int end) {
while (start < end) swap(arr[start++], arr[end--]);
}
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if (n == 1) return;
int i = n - 2, j = n - 1;
while (i >= 0 && nums[i] >= nums[i + 1]) --i;
if (i >= 0) {
j = n - 1;
while (j >= 0 && nums[i] >= nums[j]) --j;
swap(nums[i], nums[j]);
}
reverse(nums, i + 1, n - 1);
}
void display(vector<int>& nums) {
cout << "[";
string str = "";
for(auto i : nums) {
cout <<str<< i;
str = ", ";
}
cout << "]"<<endl;
}
};
int main() {
vector<int> nums1{1, 2, 3};
vector<int> nums2{3, 2, 1};
vector<int> nums3{1, 1, 5};
vector<int> nums4{1};
Solution s;
s.nextPermutation(nums1);
s.display(nums1);
s.nextPermutation(nums2);
s.display(nums2);
s.nextPermutation(nums3);
s.display(nums3);
s.nextPermutation(nums4);
s.display(nums4);
return 0;
}