8 条题解

  • 0
    @ 2024-4-8 21:00:50

    提供两种解法:

    next_permutation

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 20;
    int a[N];
    int n;
    int main(){
        scanf("%d",&n);
        for (int i = 1; i <= n; ++i) {
            a[i] = i;
        }
        do{
            for (int i = 1; i <= n; ++i) {
                printf("%d ",a[i]);
            }
            printf("\n");
        }while(next_permutation(a + 1,a + n + 1));
        return 0;
    }
    

    DFS

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 20;
    int vis[N];
    int a[N];
    int n;
    void dfs(int x){
        if (x > n) {
            for (int i = 1; i <= n; ++i) {
                printf("%d ",a[i]);
            }
            printf("\n");
        }
        for (int i = 1; i <= n; ++i) {
            if(!vis[i]) {
                vis[i] = 1;
                a[x] = i;
                dfs(x + 1);
                a[x] = 0;
                vis[i] = 0;
            }
        }
    }
    int main(){
        scanf("%d",&n);
        dfs(1);
        return 0;
    }
    

    信息

    ID
    82
    时间
    2000ms
    内存
    512MiB
    难度
    5
    标签
    递交数
    399
    已通过
    155
    上传者