题目描述
排列与组合是常用的数学方法,其中组合就是从n个元素中抽出r个元素(不分顺序),我们可以简单地将nn个元素理解为自然数1,2,…,n,从中任取r个数。
现要求你输出所有组合。
输入格式
一行两个自然数n,r(1<n<21),(0≤r≤n)。
输出格式
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
输入输出样例
输入 #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
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-03-14 12:55:31
* @LastEditTime: 2022-03-14 19:16:56
*/
#include<bits/stdc++.h>
using namespace std;
int n,r;
int a[(int)1e6+10];
bool b[(int)1e6+10];
void dfs(int x)
{
if(x==r+1){
for(int i=1;i<=r;i++)
cout<<setw(3)<<a[i];
cout<<endl;
return;
}
for(int i=a[x-1]+1;i<=n;i++){
a[x]=i;
dfs(x+1);
}
}
int main()
{
cin>>n>>r;
dfs(1);
}