递归实现组合型枚举

从 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 

AC代码

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int way[50];
int n, m;
void dfs(int cnt, int start)
{
	if (cnt > m)
	{
		for (int i = 1; i <= m; i++)
		{
			printf("%d ", way[i]);
		}
		printf("\n"); 
		return;
	}
	for (int i = start; i <= n; i++)
	{
		way[cnt] = i;
		dfs(cnt + 1, i + 1);
	}
}
int main()
{
	cin >> n >> m;
	dfs(1, 1);
	return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
int n, m;
int ans[50];
void dfs(int step, int cnt)
{
	if (cnt == m)
	{
		for (int i = 1; i <= m; i++)
		{
			printf("%d ", ans[i]);
		}
		printf("\n");
		return ;
	}
	if (step == n)
	{
		return;
	}
	cnt++;
	ans[cnt] = step + 1;
	dfs(step + 1, cnt);
	ans[cnt] = 0;
	cnt--;
	dfs(step + 1, cnt);
}
int main()
{
	cin >> n >> m;
	dfs(0, 0);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值