0分求助

B3623 枚举排列(递归实现排列型枚举)

MESSI_ @ 2024-04-21 18:25:28

#include<bits/stdc++.h>
using namespace std;
int n,m,a[10001],mark[10001];
void dfs(int k){
    if(k==n+1){
        for(int i=1;i<=m;i++){
            cout << a[i] <<" ";
        }
        cout << endl;
        return;
    }
    else{
        for(int i=1;i<=n;i++){
            if(!mark[i])
            mark[i]==1;
            a[k]=i;
            dfs(k+1);
            mark[i]==0;
        }
    }
}
int main(void){
    cin >> n >> m;
    dfs(1);
    return 0;
}

by W_Galaxy @ 2024-04-21 18:38:21

#include<bits/stdc++.h>
using namespace std;
int n,m,a[10001],mark[10001];
void dfs(int k){
    if(k==m+1){//将 m 作为递归的结束条件
        for(int i=1;i<=m; i++){
            cout << a[i] << " ";
        }
        cout << endl;
        return;
    } else{
        for(int i=1;i<=n;i++){
            if(!mark[i])
                mark[i]=1; //赋值
                a[k]=i;
                dfs(k+1);
                mark[i]=0; //同上
        }
    }
}
int main(void){
    cin >> n >> m;
    dfs(1);
    return 0;
}

by W_Galaxy @ 2024-04-21 18:39:53

@MESSI_


by MESSI_ @ 2024-05-01 18:49:51

@W_Galaxy

一个WA一个TLE


by xiaohuanxiong @ 2024-05-25 08:25:01

你参考一下

#include<bits/stdc++.h>
using namespace std;
int n,k; 
int ans[11]={};
int dis[11]={}; 
void dfs(int num,int step)
{
    ans[step]=num;
    if (step==k)
    {
        for (int i=1;i<=step;i++)
        {
            cout<<ans[i]<<" ";
        }   
        cout<<endl;
        return ;
    }
    for (int i=1;i<=n;i++)
    {
        if (dis[i]!=1)
        {
            dis[i]=1;
            dfs(i,step+1);
            dis[i]=0;
        }   
    }
}
int main()
{
    cin>>n>>k;
    for (int i=1;i<=n;i++)
    {
        memset(dis,0,sizeof(dis));
        dis[i]=1;
        dfs(i,1);
    }
    return 0;
}

|