C++ recursively implement exponential enumeration

Randomly select any number of n integers from 1 to n, and output all possible options.
Input format
Enter an integer n.
Output format
One scheme is output per line.
The numbers in the same line must be arranged in ascending order, and two adjacent numbers are separated by exactly 1 space.
For schemes without any number selected, a blank line is output.
This question has a custom validator (SPJ), and the order between the lines (different schemes) is arbitrary.
Data range
1≤n≤15
Input example:
3
Output example:
3
2
2 3
1
1 3
1 2
1 2 3

AC code:

#include<iostream>
#include<string.h>

using namespace std;

int n;
int change[16];

void dfs(int index)//枚举选index和不选index的情况
{
    
    
    if(index==n+1){
    
    
        for(int i=1;i<=n;++i)//被选就输出
        {
    
    
            if(change[i]) cout<<i<<" ";
        }
        cout<<endl;
        return;
    }

    for(int i=0;i<2;++i)//0为不选,1为选
    {
    
    
        change[index]=i;
        dfs(index+1);
    }
    return;
}

int main()
{
    
    
    cin>>n;
    dfs(1);//从1开始枚举选和不选
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108762332