洛谷 P10448 组合型枚举-普及-

题目描述

从 1∼n1 \sim n1∼n 这 nnn 个整数中随机选出 mmm 个,输出所有可能的选择方案。

输入格式

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

输出格式

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

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

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

输入输出样例 #1

输入 #1

复制代码
5 3

输出 #1

复制代码
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

说明/提示

对于所有测试数据满足 0≤m≤n0 \le m \le n0≤m≤n , n+(n-m) \\le 25

solution

递归枚举,对于每一个数都有选择或者不选两种状态,然后继续往下递归即可

代码

cpp 复制代码
#include <iostream>
#include "bit"
#include "vector"
#include "unordered_set"
#include "unordered_map"
#include "set"
#include "queue"
#include "algorithm"
#include "bitset"
#include "cstring"
#include "cmath"
#include "list"

using namespace std;

int n, m, a[30];

void f(int x, int k) {
    if (x > n) {
        if (k == m) {
            for (int i = 0; i < k; i++) {
                cout << a[i] << " ";
            }
            cout << endl;
        }
        return;
    }

    a[k] = x;
    f(x + 1, k + 1);
    f(x + 1, k);

}

int main() {
    cin >> n >> m;
    f(1, 0);

}

结果

相关推荐
sheeta19985 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
gfdhy11 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***060111 小时前
SpringMVC 请求参数接收
前端·javascript·算法
一个不知名程序员www12 小时前
算法学习入门---vector(C++)
c++·算法
云飞云共享云桌面12 小时前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
福尔摩斯张12 小时前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
橘颂TA12 小时前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
xxxxxxllllllshi13 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
前端小L13 小时前
图论专题(二十二):并查集的“逻辑审判”——判断「等式方程的可满足性」
算法·矩阵·深度优先·图论·宽度优先