AcWing 93: Recursive implementation of combined enumeration ← DFS

[Title source]
https://www.acwing.com/problem/content/95/

[Title description]
Randomly select m from the n integers 1∼n, and output all possible options.

[Input format]
Two integers n and m are separated by spaces on the same line.

[Output format]
Output all the schemes in ascending order, one per line.
First, the numbers in the same line are arranged in ascending order, and two adjacent numbers are separated by a space.
Secondly, for two different rows, compare the numbers corresponding to the subscripts one by one, and the one with the smaller lexicographical order is listed first (for example, 1 3 5 7 is listed before 1 3 6 8).

[Data range]
n>0, 0≤m≤n, n+(n−m)≤25

[Input example]
5 3

[Output example]
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 

[Algorithm Analysis]
All recursions correspond to a
recursive search tree .
Recursive search tree can make it easier for us to understand DFS.
The concept of " layer " can be observed more clearly .
In lexicographical order, select 2 numbers from 4 numbers, and the schematic diagram of the obtained recursive search tree is shown below.

 
【Algorithm code】

#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
*/




[Reference]
https://blog.csdn.net/qq_63391968/article/details/128809355
https://www.acwing.com/video/2731/


 

Guess you like

Origin blog.csdn.net/hnjzsyjyj/article/details/132156135