深度优先遍历

求n个数的所有排列组合。

#include "stdafx.h"
#include <stdio.h>

int a[10], book[10], n;

void dfs(int step)
{
    int i;
    if(step == n+1)
    {
        for (i = 0; i<=n; i++)
        {
            printf("%d", a[i]);
        }
        printf("
");

        return;
    }

    for (i=1; i<=n; i++)
    {
        if (book[i] == 0)
        {
            a[step] = i;
            book[i] = 1;

            dfs(step+1);
            book[i] = 0;
        }
    }
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    scanf("%d", &n);
    dfs(1);
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/cjingzm/p/4634321.html