吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2301|回复: 2
收起左侧

[C&C++ 转载] 全排列问题的递归解法

[复制链接]
KaQqi 发表于 2019-4-14 15:09
思路有两个,一个是递归,一个是栈。两者的本质都是深度优先搜索。。

直接上代码。
第一题 p1199
http://ybt.ssoier.cn:8088/problem_show.php?pid=1199
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <string.h>

int longs;
char s[27];
char solution[27];

void Output()
{
	for(int i = 0;i<longs;i++)
	{
		printf("%c",solution[i]);
	}
	printf("\n");
}

bool not_used(char x)
{
	for(int i = 0;i<=longs;i++)
	{
		if(x == solution[i])
		{
			return 0;
		}
	}
	return 1;//没被用过 
}

int Go(int count)
{
	if(count == longs)
	{
		Output();
		solution[count] = 0;
		return 0;
	}
	for(int i = 0;i<longs;i++)
	{
		if(not_used(s[i]))
		{
			solution[count] = s[i];
			Go(count+1);
			solution[count] = 0;
		}
	}
}

int main()
{
	
	scanf("%s",&s);
	longs = strlen(s);

//	printf("%c\n",s[1]);
	Go(0);
	return 0;
}


第二题 p1706
https://www.luogu.org/problemnew/show/P1706
[C++] 纯文本查看 复制代码
#include <stdio.h>

int n;
char solution[10];

void Output()
{
	for(int i = 0;i<n;i++)
	{
		printf("%5d",solution[i]);
	}
	printf("\n");
}

bool not_used(int x)
{
	for(int i = 0;i<=n;i++)
	{
		if(x == solution[i])
		{
			return 0;
		}
	}
	return 1;//没被用过 
}

int Go(int count)
{
	if(count == n)
	{
		Output();
		solution[count] = 0;
		return 0;
	}
	for(int i = 1;i<=n;i++)
	{
		if(not_used(i))
		{
			solution[count] = i;
			Go(count+1);
			solution[count] = 0;
		}
	}
}

int main()
{
	scanf("%d",&n);
	Go(0);
	return 0;
}

免费评分

参与人数 1吾爱币 +5 热心值 +1 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

zjgt 发表于 2019-4-15 14:11
想想是不是可以优化呢,比如可以用一个数组来标记对应的数字或字母是否已使用,这样就不用再遍历一遍数组来判断是否已使用
 楼主| KaQqi 发表于 2019-4-15 18:58
zjgt 发表于 2019-4-15 14:11
想想是不是可以优化呢,比如可以用一个数组来标记对应的数字或字母是否已使用,这样就不用再遍历一遍数组来 ...

是的,可以打静态表来优化
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-16 13:04

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表