【DFS】全排列

Description

列出所有数字1到数字n的连续自然数的排列,要求所产生的任一数字序列中不允许出现得复数字。

Input

输入:n(1<=n<=9)

Output

由1~n组成的所有不重复的数字序列,每行一个序列。

Sample Input

3

Sample Output

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

思路:
深搜,一个一个搜。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
int n,b[105];
bool a[105]={0};
void dfs(int k)
{
	if(k==n+1)//判断此方案是否搜完
	{
		for(int i=1;i<=n;i++)
			printf("%d ",b[i]);
		printf("\n");//输出
	}
	for(int i=1;i<=n;i++)
	{
		if(a[i]==0)//判断此数用过没
		{
			a[i]=1;//把此数判为用过
			b[k]=i;//把此数放进栈里
			dfs(k+1);
			b[k]=0;//把此数拿出栈里
			a[i]=0;//把此数判回没用过
		} 
	}
}
int main()
{
	scanf("%d",&n);
	dfs(1);//直接深搜
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/SSL_wujiajie/article/details/82712451