递归实现指数型枚举

发布时间 2023-03-22 21:12:54作者: 315K423

#include<iostream>
#include<algorithm>
#include<cstring>
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) {
printf("%d ", 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);

}