AcWing 93. 递归实现组合型枚举题解

题目链接

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

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

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

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

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

数据范围
n > 0 , n>0 , n>0,
0 ≤ m ≤ n , 0≤m≤n , 0mn,
n + ( n − m ) ≤ 25 n+(n−m)≤25 n+(nm)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 <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
typedef long long ll;
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define endl '\n'
using namespace std;
const int N = 30;
int st[N];
int num[N];
int n, m;
void dfs(int u)
{
    if (u > m)
    {
        for (int i = 1; i <= m; i++)
            cout << num[i] << " ";
        cout << endl;
        return;
    }
    for (int i = 1; i <= n; i++)
    {
        if (!st[i])
        {
            num[u] = i;
            st[i] = 1;
            dfs(u + 1);
            st[i] = 0;
        }
    }
}
int main()
{
    IOS;
    cin >> n >> m;
    dfs(1);
    return 0;
}

输出结果
结果
仔细读题才发现数字相同算同种方案,只需要按升序排列的那一种。

开始想的是记录一下当前排列数字组合是否出现,出现过就不再进行输出,想了想没有什么好的思路(orz)。然后灵机一动发现其实输出要求就是后面的数字一定比前面大,递归搜索的时候不要搜索比前一位数字还小的数字就可以了。遂修改代码

#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
typedef long long ll;
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define endl '\n'
using namespace std;
const int N = 30;
int st[N];
int num[N];
int n, m;
void dfs(int u, int i)
{
    if (u > m)
    {
        for (int i = 1; i <= m; i++)
            cout << num[i] << " ";
        cout << endl;
        return;
    }
    for (; i <= n; i++) //保证遍历的数字一定更大
    {
        if (!st[i])
        {
            num[u] = i;
            st[i] = 1;
            dfs(u + 1, i + 1);
            st[i] = 0;
        }
    }
}
int main()
{
    IOS;
    cin >> n >> m;
    dfs(1, 1);
    return 0;
}

(氵完一篇)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值