link

练习 next_permutation 函数的用法

#include <bits/stdc++.h>

using ll = long long;

auto main()->int {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    
    int n;
    std::cin >> n;

    std::vector<int> a(n);
    std::iota(a.begin(), a.end(), 1);

    do {
        std::for_each(a.begin(), a.end(), [&](int x) {
            std::cout << x << " ";
        });
        std::cout << "\n";
    } while (std::next_permutation(a.begin(), a.end()));
    
    return 0;
}

好像是要用递归实现来着,那就再写一遍吧。

#include <bits/stdc++.h>

using ll = long long;

auto main()->int {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    
    int n;
    std::cin >> n;

    std::vector<int> ans, v(n + 1);
    std::function<void(int)> dfs = [&](int x) {
        if (x > n && ans.size() == n) {
            std::for_each(ans.begin(), ans.end(), [](int x) {
                std::cout << x << " ";
            });
            std::cout << "\n";
            return ;
        }

        for (int i = 1; i <= n; ++i) {
            if (v[i]) {
                continue;
            }
            v[i] = 1;
            ans.push_back(i);
            dfs(x + 1);
            ans.pop_back();
            v[i] = 0;
        }
    };

    dfs(1);
    
    return 0;
}

4min +\textbf{\textcolor{#37A01D}{+}}