ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-01-01 14:32:47  阅读:192  来源: 互联网

标签:输出 组合型 int 题解 dfs st 93 include define


题目链接

题目描述
从 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 , 0≤m≤n,
n + ( n − m ) ≤ 25 n+(n−m)≤25 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 <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;
}

(氵完一篇)

标签:输出,组合型,int,题解,dfs,st,93,include,define
来源: https://blog.csdn.net/qq_53775064/article/details/122267180

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有