返回题解分享
讨论 / 题解分享/ 帖子详情

全排列 - 题解

提供两种解法:

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;
}
0 回复 0 转发 0 喜欢 7 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!