题目链接:P1706 全排列问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目描述
按照字典序输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
输入格式
一个整数 n。
输出格式
由 1 ~ n 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 5 个场宽。
样例 #1
样例输入 #1
3
样例输出 #1
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
提示
1 <= n <= 9。
AC code 1:(DFS)
#include<iostream>
using namespace std;
int n;
int a[10],book[10];
void dfs(int step)
{
if(step==n+1)
{
for(int i=1;i<=n;i++)
printf("%5d",a[i]);
puts("");
return ;
}
for(int i=1;i<=n;i++)
{
if(book[i]==0)
{
a[step]=i;
book[i]=1;
dfs(step+1);
book[i]=0;
}
}
return ;
}
int main()
{
cin>>n;
dfs(1);
return 0;
}
AC code 2:(STL-next_permutation)
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
string s="123456789";
do{
for(int i=0;i<n;i++)
printf("%5c",s[i]);
puts("");
}while(next_permutation(s.begin(),s.begin()+n));
}