acwing 842 排列数字 (dfs)

题面

在这里插入图片描述

题解

在这里插入图片描述

DFS 从开始填数字,标记出已经放入的数字,然后回溯,每次搜索到第三层输出答案即可

代码

#include<bits/stdc++.h>

using namespace std;
const int N = 10;

int n;
int path[N];
bool st[N];

void dfs(int u) {
    
    

    if (u == n) {
    
    
        for (int i = 0; i < n; i++) cout << path[i] << " ";
        cout << endl;
        return;
    }

    for (int i = 1; i <= n; i++) {
    
    
        if (!st[i]) {
    
    
            path[u] = i;
            st[i] = true;
            dfs(u + 1);
            st[i] = false;
        }
    }


}

int main() {
    
    

    cin >> n;
    dfs(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114306384