组合的输出
题目描述
排列与组合是常用的数学方法,其中组合就是从 n n n 个元素中抽出 r r r 个元素(不分顺序且 r ≤ n r \le n r≤n),我们可以简单地将 n n n 个元素理解为自然数 1 , 2 , … , n 1,2,\dots,n 1,2,…,n,从中任取 r r r 个数。
现要求你输出所有组合。
例如 n = 5 , r = 3 n=5,r=3 n=5,r=3,所有组合为:
123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , 345 123,124,125,134,135,145,234,235,245,345 123,124,125,134,135,145,234,235,245,345。
输入格式
一行两个自然数 n , r ( 1 < n < 21 , 0 ≤ r ≤ n ) n,r(1<n<21,0 \le r \le n) n,r(1<n<21,0≤r≤n)。
输出格式
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
注意哦!输出时,每个数字需要 3 3 3 个场宽。以 C++ 为例,你可以使用下列代码:
cout << setw(3) << x;
输出占 3 3 3 个场宽的数 x x x。注意你需要头文件 iomanip
。
样例 #1
样例输入 #1
5 3
样例输出 #1
1 2 31 2 41 2 51 3 41 3 51 4 52 3 42 3 52 4 53 4 5
AC代码:
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<queue>
#include<string>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<numeric>
#include<iomanip>
#define endl '\n'
using namespace std;typedef long long ll;
typedef pair<int, int>PII;
const int N=3e5+10;
const int MOD=998244353;
const int INF=0X3F3F3F3F;
const int dx[]={-1,1,0,0,-1,-1,+1,+1};
const int dy[]={0,0,-1,1,-1,+1,-1,+1};
const int M = 1e6 + 10;int n ,r;
int st[35];
int a[N];
int l;
void dfs(int step)
{if(step == r + 1){for(int i = 1; i <= r; i ++){cout << setw(3) << a[i];}cout << endl;return ;}for(int i = a[step - 1] + 1; i <= n; i ++){a[step] = i;dfs(step + 1);}return ;
}
int main()
{cin >> n >> r;
// for(int i = 1; i <= r; i ++)
// {
// memset(a, 0, sizeof a);
// l = i;
// dfs(i);
// }dfs(1);return 0;
}