5972 Problem A 【递归入门】全排列

本文介绍了一个使用递归方法实现的全排列算法,并提供了一个完整的C++代码示例。该算法适用于1到10之间的整数,能够按字典序输出所有可能的全排列结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 A: 【递归入门】全排列
时间限制: 1 Sec 内存限制: 128 MB
献花: 108 解决: 68
[献花][花圈][TK题库]
题目描述
排列与组合是常用的数学方法。
先给一个正整数 ( 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

#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>

using namespace std;
int Max, Array[16];
bool hashTable[16] = { 0 };

void Generate(int n)
{
    if (n > Max)
    {
        for (int i = 1; i <= Max; ++i)
        {
            printf("%d", Array[i]);
            if (i != Max)
                printf(" ");
        }
        printf("\n");
        return;
    }

    for (int i = 1; i <= Max; ++i)
    {
        if (hashTable[i] == false)
        {
            Array[n] = i;
            hashTable[i] = true;
            Generate(n + 1);
            hashTable[i] = false;
        }
    }
}

int main()
{
#ifdef _DEBUG
    freopen("data.txt", "r+", stdin);
#endif // _DEBUG

    while (cin >> Max)
    {
        Generate(1);
    }



    return 0;
}
/**************************************************************
    Problem: 5972
    User: Sharwen
    Language: C++
    Result: 升仙
    Time:41 ms
    Memory:1704 kb
****************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值