简单全排列

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

void dfs(int nowIndex, bool *flag, int *arr1, int n) {
    if (nowIndex == 3) {    //到达叶子结点,打印数据
        for (int i = 0; i < n; i++)
            printf("%d\t", arr1[i]);
        printf("\n");
    } else {
        for (int i = 1; i <= 3; i++) {//遍历每个数字,将其填入arr1[nowIndex]
            if (flag[i] == false) {//目标数i未填入任何位置
                arr1[nowIndex] = i;
                flag[i] = true;
                dfs(nowIndex + 1, flag, arr1, n);
                flag[i] = false;
            }
        }
    }
}

int main() {
    int *arr1 = new int[3];
    bool *flag = new bool[3];
    //初始化数组
    memset(arr1, 0, sizeof(arr1));
    memset(flag, false, sizeof(flag));
    //从0位置开始
    dfs(0, flag, arr1, 3);
    return 0;
}

//计算N的全排列
#include <iostream>
#include <cstdio>

using namespace std;
int *arr1;
bool *flag;
int N;
int count = 0;

void dfs(int index) {
    if (index == N) {
        for (int i = 0; i < N; i++)
            printf("%d\t", arr1[i]);
        printf("\n");
        count++;
    } else {
        for (int i = 1; i <= N; i++) {
            if (flag[i] == false) {
                arr1[index] = i;
                flag[i] = true;
                dfs(index + 1);
                flag[i] = false;
            }
        }
    }
}

int main() {
    scanf("%d", &N);
    arr1 = new int[N];
    flag = new bool[N + 1];
    dfs(0);
    printf("%d", count);
    delete[] arr1;
    delete[] flag;

    return 0;
}

发布了29 篇原创文章 · 获赞 2 · 访问量 449
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览