全排列实现,附蓝桥杯例题

目录

123的全排列

具体代码: 

带分数代码实现


123的全排列

如下图,使用递归树展现,枚举位置。

具体代码: 

#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

#define N 100

int a[N];
int n,m;
int mem[N];
bool st[N];

void dfs(int x) //x是当前位置 
{	
	if(x > 2)
	{
		for(int i = 0; i < 3; i ++)	
		{
			cout<<a[i];
		}
		cout<<endl;
		return ;
	}
	
	for(int i = 1; i <= 3; i ++)
	{
		if(!st[i])
		{
			a[x] = i;
			st[i] = true; // 标记为使用过
			dfs(x + 1); //深搜
			st[i] = false; // 回溯,撤销处理结果
		}
	}
	
}

int main()
{
	dfs(0);
	return 0;
}

 相关例题:

全排列

P1706 全排列问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

带分数

“蓝桥杯”练习系统 (lanqiao.cn)

 

例如:
  用户输入:
  100
  程序输出:
  11

  再例如:
  用户输入:
  105
  程序输出:
  6 

思路详解

1.枚举1-9的全排列
2.将全排类分割成a b c 
3.判断该枚举的数组成的a b c,是否可以使等式成立
    成立的话,res++; 

带分数代码实现

#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

#define N 100

int a[N];
int n,m;
int mem[N];
int st[N];
int res;
int calculate(int l, int r) //计算a b c
{
	int res = 0;
	for(int i = l; i <= r; i++)
	{
		res = res * 10 + a[i];
	}
	return res;
}

void dfs(int x)
{
	if(x > 8)
	{
		for(int i = 0; i < 9 - 2; i ++)
		{
			for(int j = i + 1; j < 9 - 1; j++)
			{
				int a = calculate(0, i);
				int b = calculate(i + 1, j);
				int c = calculate(j + 1, 8);
				//if( n == a + b / c)
				if( n * c == (a * c + b))
					res++;
			}
		}
		return ;
	}
	
	for(int i = 1; i <= 9; i ++)
	{
		if(!st[i])
		{
			a[x] = i;
			st[i] = true;
			dfs(x + 1);
			st[i] = false;
		}
	}
}

/*思路 
1.枚举1-9的全排列
2.将全排类分割成a b c 
3.判断该枚举的数组成的a b c,是否可以使等式成立
	成立的话,res++; 
*/
int main()
{
	scanf("%d",&n);
	dfs(0);
	printf("%d",res);
	return 0;
}

两道例题

 全排列

P1706 全排列问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

带分数

“蓝桥杯”练习系统 (lanqiao.cn)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值