题目描述
按照字典序输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
输入格式
一个整数 n。
输出格式
由 1 ∼n 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 5 个场宽。
输入输出样例
输入 #1
3
输出 #1
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
说明/提示
1≤n≤9。
全排列问题,采用递归的方法,遍历每一个元素,used数组判断该数字是否已经遍历过,ans输出保存答案,cnt则记录已经遍历的数字的个数,然后进行递归,递归完后进行还原之前的状态。
还是不多说了直接上代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 9+1;
bool used[maxn];
int ans[maxn];
int n;
void print() {
for (int i = 1; i <= n; i++)
printf("%5d", ans[i]);
printf("\n");
}
void dfs(int cnt) {
if (cnt == n) {
print(); return;
}
for (int i = 1; i <= n; i++) {
if (used[i] == false)
{
used[i] = true;
cnt++;
ans[cnt] = i;
dfs(cnt);
cnt--;
used[i] = false;
}
}
}
int main() {
cin >> n;
dfs(0);
return 0;
}
该博客介绍了如何使用递归方法解决1到n的全排列问题,详细讲解了输入输出格式、样例,并提供了C++实现代码。通过一个布尔数组used记录已使用数字,递归遍历并避免重复,最后输出所有排列。
701





