组合的输出 (dfs+记忆化)

5720: 组合的输出 分享至QQ空间

时间限制(普通/Java):1000MS/3000MS     内存限制:65536KByte
总提交: 105            测试通过:58

描述

 

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

现要求你用递归的方法输出所有组合。

例如n=5,r=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

 

输入

 

一行两个自然数n、r(1<n<21,1≤r≤n)。

输出

 

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

样例输入

样例输出

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 typedef long long ll;
 8 int n,k;
 9 int arr[25];
10 
11 void dfs(int ee,int rr){
12     arr[ee]=rr;
13     if(ee==k){
14         for(int i=1;i<=k;i++) printf("%3d",arr[i]);
15         printf("\n");
16         return;
17     }
18     for(int i=rr+1;i<=n;i++){
19         dfs(ee+1,i);
20     }
21 }
22 
23 int main(){
24     ios::sync_with_stdio(false);
25     cin>>n>>k;
26     dfs(0,0);
27 }
View Code

猜你喜欢

转载自www.cnblogs.com/qq-1585047819/p/11357390.html
今日推荐