C++ recursively implement combined enumeration

Randomly select m from the n integers from 1 to n, and output all possible options.
Input format
Two integers n, m
, separated by spaces on the same line.
Output format
All schemes are output in order from smallest to largest, one per line.
First, the numbers in the same row are arranged in ascending order, and two adjacent numbers are separated by a space.
Secondly, for two different rows, the numbers corresponding to the subscripts are compared one by one, and the one with the smaller lexicographic order is ranked first (for example, 1 3 5 7 is ranked before 1 3 6 8).
Data range
n>0,0≤m≤n ,n+(n−m)≤25
Input example:
5 3
Output example:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

AC code:

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

using namespace std;

int n,m;
int change[26];

void dfs(int index,int last)//决策index时还有last个数没选
{
    
    
    if(last==0&&index<=n+1){
    
    //选完了,且选的范围合法,输出
        for(int i=1;i<=n;++i)
        {
    
    
            if(change[i]) printf("%d ",i);
        }
        printf("\n");
        return;
    }
    for(int i=1;i>=0;--i)
    {
    
    
        if(index<=n){
    
    //超出选择范围不讨论
            change[index]=i;
            dfs(index+1,last-i);
        }
    }
    return;
}

int main()
{
    
    
    cin>>n>>m;
    dfs(1,m);//从1开始决策m位的选择
    return 0;
}

Guess you like

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