-
Notifications
You must be signed in to change notification settings - Fork 0
/
31-NextPermutation.cpp
57 lines (53 loc) · 1.47 KB
/
31-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
49
50
51
52
53
54
55
56
57
/*=============================================================================
# FileName: 31-NextPermutation.cpp
# Desc: AC, 12ms
# Author: Jian Huang
# Email: [email protected]
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-08-06 15:02:17
# History:
=============================================================================*/
#include <leetcode.h>
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.empty()) {
return ;
}
int len = nums.size(), i = len - 1, j = len - 1;
while (i > 0 && nums[i] <= nums[i - 1]) {
i --;
}
if (i == 0) {
while (i < j) {
swap(nums[i ++], nums[j --]);
}
return ;
}
i --;
while (nums[j] <= nums[i]) {
j --;
}
swap(nums[i], nums[j]);
j = len - 1, i ++;
while (i < j) {
swap(nums[i ++], nums[j --]);
}
return ;
}
};
int main() {
vector<int> vec;
for (int i = 0; i < 4; i ++) {
vec.push_back(i);
}
Solution solution;
for (int j = 0; j < 3; j ++) {
solution.nextPermutation(vec);
for (int i = 0; i < 4; i ++) {
cout << vec[i] << " ";
}
cout << endl;
}
}