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("\n");
}
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("\n");
}
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;
}
    原文作者:DFS
    原文地址: https://www.cnblogs.com/xianyue/p/7413650.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞