-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
70 lines (64 loc) · 1.39 KB
/
main.cpp
File metadata and controls
70 lines (64 loc) · 1.39 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
/***
Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, just reverse nums and done.
Find the largest index l > k such that nums[k] < nums[l].
Swap nums[k] and nums[l].
Reverse the sub-array nums[k + 1:].
***/
class Solution
{
public:
void nextPermutation(vector<int>& nums)
{
int n = nums.size(), k, l;
if(n < 1) return ;
for(k = n - 2; k >= 0; --k)
{
if(nums[k] < nums[k + 1])
break;
}
if(k < 0)
reverse(nums.begin(), nums.end());
else
{
for(l = n - 1; l > k; --l)
{
if(nums[k] < nums[l])
break;
}
swap(nums[k], nums[l]);
reverse(nums.begin() + k + 1, nums.end());
}
}
};
// next_permutationµÄʹÓÃ
/*
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() == 0)
return ;
if(next_permutation(nums.begin(), nums.end()))
{
}
else{
sort(nums.begin(), nums.end());
}
}
};
*/
int main()
{
Solution s;
vector<int> nums = {1,2,3};
s.nextPermutation(nums);
for(int i = 0; i < nums.size(); ++i)
{
cout << nums[i] << endl;
}
return 0;
}