WA 67,求助

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

最萌軒宇 @ 2022-10-23 18:40:43

代码:

#include <cstdio>
using namespace std;
int n, k, a[15], use[15];
void dfs(int pos) {
    if(pos == n + 1) {
        for(int i = 1; i <= k; i++) {
            printf("%d ", a[i]);
        }
        printf("\n");
        return;
    }
    for(int i = 1; i <= n; i++) {
        if(!use[i]) {
            use[i] = 1;
            a[pos] = i;
            dfs(pos + 1);
            use[i] = 0;
        }
    }
}
int main() {
    scanf("%d%d", &n, &k);
    dfs(1);
    return 0;
}

为啥会WA?


by Kev1nL1kesCod1ng @ 2022-10-23 18:47:28

输出有重复


by 最萌軒宇 @ 2022-10-25 12:52:08

@KevinLikesCoding 具体是哪一行的重复呢?谢谢


by Kev1nL1kesCod1ng @ 2022-10-25 18:00:28

第五行有问题

#include <cstdio>
using namespace std;
int n, k, a[15], use[15];
void dfs(int pos) {
    if(pos == k + 1) {
        for(int i = 1; i <= k; i++) {
            printf("%d ", a[i]);
        }
        printf("\n");
        return;
    }
    for(int i = 1; i <= n; i++) {
        if(!use[i]) {
            use[i] = 1;
            a[pos] = i;
            dfs(pos + 1);
            use[i] = 0;
        }
    }
}
int main() {
    scanf("%d%d", &n, &k);
    dfs(1);
    return 0;
}

|