递归全排列、DFS

递归全排列

题目描述

排列与组合是常用的数学方法。
先给一个正整数 ( 1 < = n < = 10 )
例如n=3,所有组合,并且按字典序输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

输入

输入一个整数n( 1<=n<=10)

输出

输出所有全排列

每个全排列一行,相邻两个数用空格隔开(最后一个数后面没有空格)

样例输入

3

样例输出

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

思路

这题可以用递归进行深度优先搜索遍历所有的情况,也可以使用C++算法里的next_permutation函数,更为简洁

代码

//递归遍历
#include <cstdio>
#include <vector>

using namespace std;

int n;
int mp[15];
vector<int> tmp;

void print_ans()
{
    printf("%d", tmp[0]);
    for (int i = 1; i < n; ++i)
    {
        printf(" %d", tmp[i]);
    }
    printf("\n");
}

void dfs()
{
    if (tmp.size() == n)
    {
        print_ans();
        return;
    }
    for (int i = 1; i <= n; ++i)
    {
        if (mp[i])
        {
            continue;
        }
        mp[i] = 1;
        tmp.push_back(i);
        dfs();
        tmp.pop_back();
        mp[i] = 0;
    }
}

int main()
{
    while (scanf("%d", &n) != EOF)
    {
        dfs();
    }
    return 0;
}
//next_permutation
#include <cstdio>
#include <algorithm>
int main()
{
    int n;
    int arr[15] = {0};
    while (scanf("%d", &n) != EOF)
    {
        for (int i = 1; i <= n; ++i)
        {
            arr[i] = i;
        }
        do
        {
            bool flag = false;
            for (int i = 1; i <= n; ++i)
            {
                if (flag)
                {
                    printf(" %d", arr[i]);
                }
                else
                {
                    printf("%d", arr[i]);
                    flag = true;
                }
            }
            printf("\n");
        } while (next_permutation(arr + 1, arr + n + 1));
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值