问题标题: 酷町堂:谁来帮帮我?

0
1
已解决
尤博扬
尤博扬
初级光能
初级光能

1012   组合的输出经验值:800

题目描述 Description

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

输入描述 Input Description

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

输出描述 Output Description

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

样例输入 Sample Input

5 3

样例输出 Sample Output

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


0
0
沙宸安
沙宸安
中级启示者
中级启示者

搜  索  与  回  溯

0
0
0
0
0
康曦
康曦
中级光能
中级光能

学校老师教的

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m,a[100],tot;
bool c[100];
void kx2(){
    for(int i=1;i<=m;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
void kx(int t){
    if(t>m){
        kx2();
        tot++;
        return ;
    }
    for(int i=1;i<=n;i++){//全排列改成《=m 
        if(!c[i]&&i>a[t-1]){
            a[t]=i;
            c[i]=true;
            kx(t+1);
            c[i]=false;
        }
    }
}
int main(){
    cin>>n>>m;
    memset(c,false,sizeof(c));
    kx(1);
    //cout<<tot<<endl;
    return 0;
}

 

我要回答