开卷门
题目:
从 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
递归实现组合型枚举和上篇递归实现指数型枚举很像,只有递归结束条件的时候要根据题目要求进行剪枝操作,😊详情请参考https://blog.csdn.net/lymww/article/details/121780224
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#define ll long long
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
#define IOS std::ios::sync_with_stdio(false);
using namespace std;
const int N = 101;
int n, m;
vector<int> num;
void dfs(int x)
{
if(num.size() > m || num.size() + (n - x + 1) < m) return; // 剪枝
if(x == n + 1)
{
for(int i = 0; i < num.size(); i ++)
cout << num[i] << " ";
cout << endl;
return;
}
num.push_back(x);
dfs(x + 1);
num.pop_back();
dfs(x + 1);
}
int main()
{
IOS;
cin >> n >> m;
dfs(1);
return 0;
}