題目連結

觀察(右到左)!

AC Code

 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
80
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// tree node stuff here...

#endif

static int __initialSetup = []()
{
    // toggle off cout & cin, instead, use printf & scanf
    std::ios::sync_with_stdio(false);
    // untie cin & cout
    cin.tie(NULL);
    return 0;
}
();

class Solution
{
public:
    void nextPermutation(vector<int> &nums)
    {
        int n = nums.size();
        bool hasSwap = false;
        int i;
        for (i = n - 1; i >= 0; i--) {
            int mn_mx = INT_MAX, idx = -1;
            for (int j = i + 1; j < n; j++) {
                if (nums[i] < nums[j] && nums[j] < mn_mx) {
                    mn_mx = nums[j];
                    idx = j;
                }
            }
            if (idx == -1)
                continue;

            swap(nums[i], nums[idx]);
            hasSwap = true;
            break;
        }
        if (hasSwap == false) {
            sort(nums.begin(), nums.end());
            return;
        }

        for (i = i + 1; i < n; i++) {
            int mn = nums[i], idx = -1;
            for (int j = i + 1; j < n; j++) {
                if (nums[j] < mn) {
                    mn = nums[j];
                    idx = j;
                }
            }

            if (idx == -1)
                continue;
            swap(nums[i], nums[idx]);
        }
    }
};

#ifdef LOCAL
int main()
{
    Solution s;
    vector<int> inp({1, 2, 3});
    for (auto i : inp)
        printf("%d ", i);
    puts("");
    for (int r = 0; r < 6; r++) {
        s.nextPermutation(inp);
        for (auto i : inp)
            printf("%d ", i);
        puts("");
    }
    return 0;
}
#endif