-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path031_Next_Permutation.cpp
79 lines (77 loc) · 1.65 KB
/
031_Next_Permutation.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include"struct_define.h"
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
class Solution
{
public:
void nextPermutation2(vector<int>& nums)
{
for(int j = nums.size()-1; j >= 0; j--)
{
for(int i = nums.size()-1; i > j ; i--)
{
if(nums[i] > nums[j])
{
swap(nums[j],nums[i]);
sort(nums.begin()+j+1, nums.end());
return;
}
}
}
sort(nums.begin(),nums.end());
}
void nextPermutation(vector<int>& nums)
{
int j = nums.size()-1;
while ( j >= 1 && nums[j] <= nums[j-1])
{
j--;
}
if( j >= 1)
{
int k = nums.size() - 1;
while (nums[k] <= nums[j-1])
{
k--;
}
swap(nums[k], nums[j-1]);
}
sort(nums.begin()+j, nums.end());
for(auto e: nums)cout<<e;
cout<<endl;
}
void Permuate(vector<int>& nums)
{
auto init = nums;
while (true)
{
nextPermutation(nums);
if(nums == init)break;
}
}
};
int main(int argc, char const *argv[])
{
Solution sol;
vector<int> nums{1,4,3,2};
sol.nextPermutation(nums);
nums={1,3,4,2};
sol.nextPermutation(nums);
nums={1,5,1};
sol.nextPermutation(nums);
nums={5,7,8,2,3,1,9,6};
sol.nextPermutation(nums);
cout<<endl;
nums={1,2,3,4};
sol.Permuate(nums);
return 0;
}