[数据结构 & 算法] codevs1294全排列

题目描述 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

这题唯一的要注意一点就是,如果用c++的cout进行输出的话,会超时,这是我之前没有遇到的问题,纯c的printf效率要比cout高,所以这题我用printf输出

#include <stdio.h>
#include<algorithm>
#include <memory.h>
using namespace std;
int visited[11];//标记数字有没有被使用过
int a[11];//存放排列的数字
int n;//输入

void A(int x)//x的意义是现在需要选择第x位置的数字
{
	if (x==n+1)//当需要选择第n+1个位置的数字时,意味着已经排列好了n个位置,则达到要求,返回
	{
		for (int i=1;i<=n;i++)
			printf("%d ", a[i]);//打印
		printf("\n");
		return;
	}

	for (int i=1;i<=n;i++)//从1到n遍历
	{
		if (visited[i]==0)//如果没有被使用过
		{
			a[x] = i;
			visited[i] = 1;
			A(x + 1);
			visited[i] = 0;
		}	
	}
}

int main()
{
	memset(visited, 0, sizeof(visited));
	scanf("%d", &n);
	A(1);
	scanf("%d", &n);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值