【洛谷 1157】组合的输出

发布时间 2023-08-19 16:03:08作者: #Cookies#

# 组合的输出

## 题目描述

排列与组合是常用的数学方法,其中组合就是从 $n$ 个元素中抽出 $r$ 个元素(不分顺序且 $r \le n$),我们可以简单地将 $n$ 个元素理解为自然数 $1,2,\dots,n$,从中任取 $r$ 个数。

现要求你输出所有组合。

例如 $n=5,r=3$,所有组合为:

$123,124,125,134,135,145,234,235,245,345$。

## 输入格式

一行两个自然数 $n,r(1<n<21,0 \le r \le n)$。

## 输出格式

所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。

**注意哦!输出时,每个数字需要 $3$ 个场宽。以 C++ 为例,你可以使用下列代码:**

```cpp
cout << setw(3) << x;
```

输出占 $3$ 个场宽的数 $x$。注意你需要头文件 `iomanip`。

## 样例 #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
```

题解:优化DFS即可求解

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<bits/stdc++.h>
using namespace std;
int n,m,a[21],vis[21];

void dfs(int now,int last){
    if(now==m+1){
        for(int i=1;i<=m;i++)
            cout << setw(3) << a[i];
        printf("\n");
    }
    for(int i=last;i<=n;i++){
        if(vis[i]==1) continue;
        vis[i]=1;
        a[now]=i;
        dfs(now+1,i+1);
        vis[i]=0;
    }
}

int main(){
    //freopen("zuhe.in","r",stdin);
    //freopen("zuhe.out","w",stdout);
    scanf("%d %d",&n,&m);
    dfs(1,1); 
    return 0;
}