AcWing 93:递归实现组合型枚举 ← DFS

【题目来源】
https://www.acwing.com/problem/content/95/

【题目描述】
从 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 

【算法分析】
所有递归,都对应一棵
递归搜索树
递归搜索树可以让我们更加容易的理解 DFS。能够更清晰观察“
”的概念。
按字典序,从4个数中选2个,得到的递归搜索树的示意图如下所示。

 
【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=30;
int n,m;
int path[maxn];
void dfs(int level,int start) {
    if(level>m) {
        for(int i=1; i<=m; i++) printf("%d ",path[i]);
        printf("\n");
    } else {
        for(int i=start; i<=n; i++) {
            path[level]=i;
            dfs(level+1,i+1);
        }
    }
}

int main() {
    scanf("%d %d",&n,&m);
    dfs(1,1);
    return 0;
}


/*
in:
5 3

out:
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
*/




【参考文献】
https://blog.csdn.net/qq_63391968/article/details/128809355
https://www.acwing.com/video/2731/


 

猜你喜欢

转载自blog.csdn.net/hnjzsyjyj/article/details/132156135