全排列问题DFS实现执行示意图

【全排列问题DFS实现执行示意图】

【示意图依托的核心代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
 
const int maxn=12;
int a[maxn],st[maxn];
int n;
 
//确定第pos位及后续位置的值
void dfs(int pos) {
    if(pos==n+1) {
        for(int i=1; i<=n; i++) {
            printf("%5d",a[i]);
        }
        printf("\n");
        return;
    }
 
    //枚举所有数字,尝试为当前位置pos选择一个可用值
    for(int i=1; i<=n; i++) {
        if(st[i]==0) {
            a[pos]=i;
            st[i]=1;
            dfs(pos+1);
            st[i]=0; //撒销选择
        }
    }
}
 
int main() {
    scanf("%d",&n);
    dfs(1);
    return 0;
}
 
/*
in:
3

out:
    1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1
*/

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/148295326

相关推荐
YL2004042620 小时前
048路径总和III
数据结构·dfs
️是781 天前
信息奥赛一本通—编程启蒙(3395:练68.3 车牌问题)
数据结构·c++·算法
故事和你911 天前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论
paeamecium1 天前
【PAT甲级真题】- String Subtraction (20)
数据结构·c++·算法·pat考试·pat
-To be number.wan1 天前
为什么关系数据库主要采用b+树、散列表来构建索引
数据结构·b树·散列表·数据库系统
澈2071 天前
滑动窗口算法:双指针高效解题秘籍
数据结构·c++·算法
如竟没有火炬1 天前
字符串相乘——int数组转字符串
开发语言·数据结构·python·算法·leetcode·深度优先
pluviophile_s1 天前
数据结构:第1讲:算法分析
数据结构·笔记
白藏y1 天前
【数据结构】简单选择排序
数据结构·算法·排序算法
信奥胡老师1 天前
B3930 [GESP202312 五级] 烹饪问题
开发语言·数据结构·c++·学习·算法