zoukankan      html  css  js  c++  java
  • caioj 1031: [视频]递归1(全排列)【DFS】【全排列】

    题目大意:先给一个正整数 n( 1 < = n < = 10 ),输出1到n的所有全排列。
    题解:这道题目我们可以用递归来实现,递归在图论中又称为“深度优先搜索”(Depth First Search,DFS),所以在平时我们经常把用到递归的算法简称为DFS。
    我们假设a[i]表示当前排列第i个数的值,用vis表示在当前递归的时候数值i有没有出现在之前的排列数中,则我们可以用下面的dfs(int index)来实现找出全排列的算法。
    其中,index表示当前判断到第index个排列数(即编号从0到i-1这前i个排列中的数已经找好了,现在在找第i个排列数)。
    代码如下:

    #include <cstdio>
    #include <cstring>
    int n, a[11];
    bool vis[11];
    void output()
    {
        printf("%d", a[0]);
        for (int i = 1; i < n; i ++)
            printf(" %d", a[i]);
        printf("
    ");
    }
    void dfs(int idx)
    {
        if (idx == n)
        {
            output();
            return;
        }
        for (int i = 1; i <= n; i ++)
        {
            if (!vis[i])
            {
                vis[i] = true;
                a[idx] = i;
                dfs(idx+1);
                vis[i] = false;
            }
        }
    }
    int main()
    {
        while (~scanf("%d", &n))
        {
            memset(vis, false, sizeof(vis));
            dfs(0);
        }
        return 0;
    }
    
    

    除此之外,C++的STL中的algorithm库中为我们提供了next_permutation函数,它用于根据当前的排列推测出接下来的那个排列。
    我们现在可能还没有接触到排列组合的问题,但是学过排列组合问题以后我们将会知道1到n这n个数能够组成的排列的个数是n!(=n(n-1)……*1)
    所以我们可以开一个for循环,循环体内调用next_permutation,知道找到n!个排列,代码如下:

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int n, a[11];
    void output()
    {
        printf("%d", a[0]);
        for (int i = 1; i < n; i ++)
            printf(" %d", a[i]);
        printf("
    ");
    }
    int main()
    {
        while (~scanf("%d", &n))
        {
            int tot = 1;
            for (int i = 2; i <= n; i ++)
                tot *= i;
            for (int i = 0; i < n; i ++)
                a[i] = i + 1;
            output();
            for (int i = 1; i < tot; i ++)
            {
                next_permutation(a, a+n);
                output();
            }
        }
        return 0;
    }
    
    
  • 相关阅读:
    linux安装mysql5.7.24
    如何解决svn Authorization failed错误
    vux配置i18n
    vue项目使用vux框架配置教程
    EL函数
    Android的taskAffinity对四种launchMode的影响
    Activity生命周期-Android
    为什么用服务不用线程-Android
    Hibernate总结--MyEclipse的小bug
    EL表达式隐含对象
  • 原文地址:https://www.cnblogs.com/xianyue/p/7413650.html
Copyright © 2011-2022 走看看