104.全排列(深搜)搜索与回溯

1294 全排列

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
题目描述 Description

给出一个n, 请输出n的所有全排列

输入描述 Input Description

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

输出描述 Output Description

一共n!行,每行n个用空格隔开的数,表示n的一个全排列。并且按全排列的字典序输出。

样例输入 Sample Input

3

样例输出 Sample Output

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

数据范围及提示 Data Size & Hint

分类标签 Tags 点此展开 

代码:
#include< cstdio >
#include< iostream >
using namespace std;
int n,visit[11];
int a[11];
void dfs(int b)
{
if(b==n+1)
{
for(int i=1;i<=n;++i)
printf("%d ",a[i]);//注意一定要把当前取得的点放到一个数组中去,到了最后时把数组输出,否则如果是深搜的时候,每找到一个就输出,会使输出的数据不全*/ 
printf("\n");
return ;
}
for(int i=1;i<=n;++i)
{
if(!visit[i])
{
visit[i]=1;//标志设为这个i已经在排列中了
a[b]=i;
dfs(b+1);
visit[i]=0;//回溯
a[b]=0;
}
}
}
int main()
{
scanf("%d",&n);
int b=1;
for(int i=1;i<=n;++i)
{
  if(!visit[i])
  {
  visit[i]=1;
  a[1]=i;
  dfs(b+1);
  visit[i]=0;
  a[1]=0;
  }
}
return 0;
 
posted @ 2016-03-20 22:44  csgc0131123  阅读(870)  评论(0编辑  收藏  举报