AcWing 92. 递归实现指数型枚举

做法1:在过程中输出

查看代码
 /*
相关词:递归,递归搜索树,深搜
*/
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int N=16;
int arr[N];//0:还没考虑。1:选。2:不选
int a;

void dfs(int n)
{
    if(n>a)
    {
        for(int i=1;i<=a;i++)
        {
            if(arr[i]==1)
                cout<<i<<' ';
        }
        puts("");
        return;
    }
    //左孩子,不选
    arr[n]=2;
    dfs(n+1);
    arr[n]=0;//回溯时保护现场
    //右孩子,选
    arr[n]=1;
    dfs(n+1);
    arr[n]=0; //回溯时保护现场
}

main()
{
    cin>>a;
    dfs(1);
}

做法2:在过程中储存,最后输出

查看代码
 #include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

const int N=16;
int arr[N];//0:还没考虑。1:选。2:不选
int a;
vector<vector<int>> ways;//存储所有情况
void dfs(int n)
{
    if(n>a)
    {
        vector<int> way;
        for(int i=1;i<=a;i++)
        {
            if(arr[i]==1)
                way.push_back(i);
        }
        ways.push_back(way);
        return;
    }
    
    arr[n]=2;
    dfs(n+1);
    arr[n]=0;
    
    arr[n]=1;
    dfs(n+1);
    arr[n]=0; 
}

int main()
{
    cin>>a;
    dfs(1);
    for(int i=0;i<ways.size();i++)
    {
        for(int j=0;j<ways[i].size();j++) cout<<ways[i][j]<<" ";
        puts("");
    }
    return 0;
}

 

posted @ 2023-01-31 13:12  尚方咸鱼  阅读(11)  评论(0编辑  收藏  举报