关注

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

DFS的三种枚举

指数型枚举

//递归  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;
}
排列型枚举

//依次枚举每个位置应该放那个数
#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;
}
组合型枚举

//依次枚举每个位置上放那个数
#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

转载自CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/2402_82371019/article/details/158356249

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--