洛谷 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);

}

结果

相关推荐
民乐团扒谱机1 天前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T1 天前
C++ stack & queue复习笔记
开发语言·笔记·算法
wy_hhxx1 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者1 天前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK1 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜1 天前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah1 天前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课1 天前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习