其他分享
首页 > 其他分享> > 1317:【例5.2】组合的输出 深搜题解

1317:【例5.2】组合的输出 深搜题解

作者:互联网

1317:【例5.2】组合的输出


时间限制: 1000 ms         内存限制: 65536 KB
提交数: 24255     通过数: 11944

【题目描述】

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

#include<bits/stdc++.h>
using namespace std;
const int N=25;
int n,r;
int path[N];//保存路径
bool st[N];//保存这个数有没有被选过 
void dfs(int x){
    if(x==r+1)//路径到头了
    {
        for(int i=1;i<=r;i++)//输出你的路径 
         cout<<setw(3)<<path[i];
        cout<<endl; 
        return; 
    } 
    
    for(int i=1;i<=n;i++)//找出合适的数存在path 
    {
        if(i>path[x-1]&&!st[i])//数比之前的数要大,而且没有被挑选过
        {
            path[x]=i; 
            st[i]=1;
            dfs(x+1);//递归去实现DFS 
            st[i]=0;//实现后当前位没有被选,所以清零 
        } 
    }
}
int main()
{
    cin>>n>>r;
    dfs(1);
    return 0; 
} 

 

 

 

标签:1317,5.2,组合,int,题解,dfs,st,path
来源: https://www.cnblogs.com/zhoe/p/15493058.html