|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <algorithm> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +#define REP(i,n) for(int i=0;i<(n);++i) |
| 7 | +#define FOR(i,a,b) for(int i=(a);i<=(b);++i) |
| 8 | +#define RFOR(i,a,b) for(int i=(a);i>=(b);--i) |
| 9 | + |
| 10 | +class Solution { |
| 11 | +public: |
| 12 | + void nextPermutation(vector<int> &num) { |
| 13 | + int n = num.size(); |
| 14 | + int idx = n - 1; |
| 15 | + while (idx - 1 >= 0 && num[idx - 1] >= num[idx]) --idx; |
| 16 | + if (--idx <= -1) { |
| 17 | + reverse(num.begin(), num.end()); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + int lt = idx + 1, rt = n - 1; |
| 22 | + while (lt <= rt) { |
| 23 | + int mt = (lt + rt) / 2; |
| 24 | + if (num[mt] <= num[idx]) { |
| 25 | + rt = mt - 1; |
| 26 | + } else { |
| 27 | + lt = mt + 1; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + swap(num[idx], num[rt]); |
| 32 | + reverse(num.begin() + idx + 1, num.end()); |
| 33 | + } |
| 34 | +}; |
| 35 | + |
| 36 | +void test(int mm[], int len) { |
| 37 | + vector<int> num; |
| 38 | + num.assign(mm, mm + len); |
| 39 | + Solution s; |
| 40 | + s.nextPermutation(num); |
| 41 | + REP(i,num.size()) cout << num[i] << " "; |
| 42 | + cout << endl; |
| 43 | +} |
| 44 | + |
| 45 | +int main() { |
| 46 | + int mm1[3] = {1, 2, 3}; |
| 47 | + test(mm1, sizeof(mm1) / sizeof(mm1[0])); |
| 48 | + |
| 49 | + int mm2[] = {3, 2, 1}; |
| 50 | + test(mm2, sizeof(mm2) / sizeof(mm2[0])); |
| 51 | + |
| 52 | + int mm3[] = {1, 1, 5}; |
| 53 | + test(mm3, sizeof(mm3) / sizeof(mm3[0])); |
| 54 | + |
| 55 | + return 0; |
| 56 | +} |
0 commit comments