zufeoj_【例5.2】组合的输出

题目链接:http://acm.ocrosoft.com/problem.php?cid=1172&pid=46


题目描述

排列与组合是常用的数学方法,其中组合就是从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)。

输出

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

样例输入

5 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


#include<bits/stdc++.h>
using namespace std;
int n,r;
int a[555];
int ans=0;
bool vis[22];
void dfs(int x){
    if(x>r){
        ans++;
        for(int i=1;i<=r;i++){
           printf("%3d",a[i]);
        }
        cout<<endl;
        return;
    }else{
        for(int i=a[x-1];i<=n;i++){
            if(vis[i]==0){
                vis[i]=1;
                a[x]=i;
                dfs(x+1);
                vis[i]=0;
            }
        }
    }
}
int main(){
    cin>>n>>r;
    a[0]=1;
    dfs(1);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37345402/article/details/80761394