【蓝桥杯基础算法】dfs(上)组合数,全排列

刚接触算法,有没有被递归又循环的dfs吓到?没关系,几个例题就可以彻底掌握!

1.全排列

1-n的全排列,如输入3,按顺序对1-3进行排列

cpp 复制代码
//枚举
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=10;
int n;
bool st[N];//true选过 ,false是没选过 
int arr[N];//存的是答案  
void dfs(int x)
{
	if(x>n)
	{for(int i=1;i<=n;i++)
	{
		printf("%5d",arr[i]);//长宽5
	}
	printf("\n");
	return ;
	}
	for(int i=1;i<=n;i++)
	{
		if(!st[i])
		{
			st[i]=true;
			arr[x]=i;
			dfs(x+1);
			st[i]=false;
			arr[x]=0;
		}
	}
}
int main()
{
	scanf("%d",&n);
	dfs(1);
	
	return 0;
}

2.组合数

题目:

答案:

cpp 复制代码
//选数
//剪枝 
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=30;
int k,n;
int q[N];
int arr[N];
int res=0;

bool is_prim(int sum)
{
	if(sum<2)return false;
	for(int i=2;i<=sum/i;i++)
	{
		if(sum%i==0)return false;
	}
	return true;
}
//求组合数,x表示当前到了哪个位置
//start表示从几开始枚举 
void dfs(int x,int start)
{
	if(((x-1)+n-start+1)<k)
	{
		return ;
	}
	if(x>k){
		int sum=0
		for(int i=1;i<=k;i++)
		{
			sum+=arr[i];
		}
		if(is_prim(sum))//是素数+1 
		{
			res++;
		}
	}
	for(int i=start;i<=n;i++)
	{
		arr[x]=q[i];
		dfs(x+1,i+1);//继续向下,深度优先 
		arr[x]=0;//恢复现场 
	}
}

int main()
{
	scanf("%d %d",&n,&k);
	dfs(1,1);
	printf("%d\n",res);
	return 0;
}
相关推荐
Dream it possible!3 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊3 小时前
算法之双指针系列(一)
算法·leetcode
十二3 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
小此方4 小时前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi5 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH5 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi6 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
zjxtxdy7 小时前
C++面向对象程序开发-类与对象
开发语言·c++
東隅已逝,桑榆非晚8 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
Eyfcom8 小时前
〖物联网终端实战 01〗UWB 室内高精度定位:仓储 AGV 与人员的厘米级轨迹追踪
物联网·算法·物流系统·快递系统·跨境物流快递系统·物联网终端实战