全排列问题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

相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水3 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1013 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080543 天前
C++常见八股
数据结构·c++·算法