递归实现指数型枚举(例)

发布时间 2023-05-27 19:28:55作者: gjkt_2001

从 1 ~ n 这n个整数中随机选取任意多个,输出所有可能的选择方案。

#include <iostream>  //C++标准库中的头文件.用于控制台输入和输出。
#include <cstring>   //用于处理字符串的函数和操作
#include <algorithm> //提供了许多常用的算法函数,用于对数据进行排序、查找、变换和操作等操作。

using namespace std;

const int N = 20;

int n;
int st[N];

void dfs(int x)
{ // x表示当前枚举到了哪个位置
    if (x > n)
    {
        for (int i = 1; i <= n; i++)
        {
            if (st[i] == 1)
            {
                printf("%d ", i);
            }
        }
        printf("\n");
        return;
    }
    //
    st[x] = 1;
    dfs(x + 1);
    st[x] = 0; // 恢复现场
    // 不选
    st[x] = 2;
    dfs(x + 1);
    st[x] = 0; // 恢复现场
}
int main()
{
    scanf("%d", &n);
    dfs(1);
    return 0;
}