问题 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
****************************************************************/