递归实现组合类型枚举

【问题描述】
从 1~n 这 n 个整数中随机选出 m 个,输出所有可能的选择方案。

【输入格式】
两个整数 n,m ,在同一行用空格隔开。

【输出格式】
按照从小到大的顺序输出所有方案,每行1个。

首先,同一行内的数升序排列,相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面(例如1 3 5 7排在1 3 6 8前面)。

【数据范围】
n > 0 ,
0 ≤ m ≤ n ,
n + (n−m) ≤ 25

【输入样例】
5 3

【输出样例】
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


题解:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 25;

int n, m;
int a[N];
bool st[N];

void dfs(int step, int num)
{
    if(step == m + 1)
    {
        for (int i = 1; i <= m; i ++) cout << a[i] << " ";
        puts("");
        
        return;
    }
    
    for (int i = num; i <= n; i ++)
    {
        if(!st[i])
        {
            a[step] = i;
            st[i] = true;
            
            dfs(step + 1, i);
            
            a[step] = 0;
            st[i] = false;
        }
    }
}

int main()
{
    cin >> n >> m;
    dfs(1, 1);
    return 0;
}
发布了63 篇原创文章 · 获赞 5 · 访问量 828

猜你喜欢

转载自blog.csdn.net/weixin_46239370/article/details/105330617