冲刺蓝桥杯-DFS板块(第一天)

DFS的三种枚举

指数型枚举
cpp 复制代码
//递归  DFS最重要的是顺序
//顺序:从1~n依次考虑每个数 选/不选
#include <bits/stdc++.h>

using namespace std;

const int N =20;
int n;
int st[N];//记录每个数的状态,0表示还没考虑,1表示选,2表示不选

void dfs(int x){//x表示枚举到了当前的那个位置
    if(x>n){
        for(int i=1;i<=n;i++){
            if(st[i]==1)
            cout << i << " ";
        }
        cout << endl;
        return;
    }
    
    //选
    st[x]=1;//上来先选
    dfs(x+1);//下一个数
    st[x]=0;//恢复现场
    //不选
    st[x]=2;//上来先不选
    dfs(x+1);//下一个数
    st[x]=0;//恢复现场
    
}

int main(){
    cin >> n;
    dfs(1);
    
    return 0;
}
排列型枚举
cpp 复制代码
//依次枚举每个位置应该放那个数
#include <bits/stdc++.h>

using namespace std;

const int N = 10;

bool st[N];//某个数是否被用过true表示选过false表示没有选过
int a[N];
int n;
//x表示当前枚举到了那个位置
void dfs(int x){
    if(x>n){
        for(int i=1;i<=n;i++){
            cout << a[i] << " ";
        }
        cout << endl;
        return;
    }
    
    for(int i=1;i<=n;i++){
        if(!st[i]){//如果没有被选过
            st[i]=true;
            a[x]=i;
            dfs(x+1);//判断下一个数
            a[x]=0;
            st[i]=false;
        }
    }
    
    
}

int main(){

    cin >> n;
    dfs(1);
    
    return 0;
}
组合型枚举
cpp 复制代码
//依次枚举每个位置上放那个数
#include <bits/stdc++.h>

using namespace std;

int n,m;
const int N  = 21;
int a[N];//记录都选了那些数

void dfs(int x,int start){//分别用来记录当前枚举到了那个位置,以及当前位置从几开始枚举
    
    if(x>m){
        for(int i=1;i<=m;i++) cout << a[i] << " ";
        cout << endl;
        return;
    }
    
    for(int i=start;i<=n;i++)
    {
        a[x]=i;
        dfs(x+1,i+1);
        a[x]=0;
        
    }
}


int main(){
    cin >> n >>m;
    
    dfs(1,1);
    
    return 0;
}

这个博主讲的十分细致值得深度了解学习,非常推荐,家人们!!!
【递推与递归 + DFS | 手把手带你画出递归搜索树】 https://www.bilibili.com/video/BV1S24y1p7iH/?share_source=copy_web&vd_source=214f528e7195022e9e1787511eda8c5a

相关推荐
想吃火锅100520 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.21 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn21 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫1 天前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
菜鸟‍1 天前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
退休倒计时1 天前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
popcorn_min1 天前
Digits 手写数字识别:随机森林多分类 + 像素级特征热力图
算法·随机森林·分类
liulilittle1 天前
拥塞控制:排水终止的两种决策:OR 与 AND
网络·tcp/ip·计算机网络·算法·信息与通信·tcp·通信
weixin_307779131 天前
从脚本执行到智能体协作:AI辅助测试能力的范式重构
运维·开发语言·人工智能·算法·测试用例
量化君也1 天前
从回测到全自动实盘交易,全天候策略需要经历哪些改造?
大数据·人工智能·python·算法·金融