dfsWA了一个点,蒟蒻求助~

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

rc_Taurus @ 2023-01-26 20:21:01

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,k,a[15];
void dfs(int step,int last){
    if(step>k){
        do{
            for(int i=1;i<=k;i++){
                cout<<a[i]<<" ";
            }cout<<endl;
        }while(next_permutation(a+1,a+k+1));
        return;
    }
    for(int i=last+1;i<=n;i++){
        a[step]=i;
        dfs(step+1,i);
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>k;
    dfs(1,0);
    return 0;
}

by __cheems__ @ 2023-01-26 21:35:30

@rc_Wechis 我觉得你没必要用last剪枝。题目并没有说排序一定是要上升的或下降的。

AC Code

#include <iostream>
using namespace std;
int n,k;
int mem[16];
bool b[16];
void dfs(int step){
    if (step > k){
        for (register int i = 1;i<=k;i++){
            cout << mem[i] << " ";
        }
        cout << endl;
        return;
    }
    for (register int i = 1;i<=n;i++){
        if (!b[i]){
            mem[step] = i;
            b[i] = 1;
            dfs(step + 1);
            mem[step] = 0;
            b[i] = 0;
        }
    }
} 
int main(){
    cin >> n >> k;
    dfs(1);
    return 0;
}

by rc_Taurus @ 2023-01-27 13:05:02

@CristianoRonaldo07 栓Q


|