递归常用的三种枚举方式

一.递归实现指数型枚举

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
bool st[20];
int n;

void dfs(int u)
{
	if(u >= n+1)
	{
		for(int i=1;i <= n;i++) if(st[i]) cout<<i<<' ';
		cout<<endl;	
		return ;
	}	
	
	st[u]=true;
	dfs(u+1);
	
	st[u]=false;
	dfs(u+1);
}

int main()
{
 	IOS;
	
	cin>>n;
	
	dfs(1);
	 	
 	return 0;
}

它的枚举策略是枚举每个数字(或者方案)要还是不要

二.递归实现组合类型枚举

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
int path[10];
int n;

void dfs(int u,int last)
{
	if(u >= 3)
	{
		for(int i=0;i < 3;i++) cout<<path[i]<<' ';
		cout<<endl;
	}
	
	for(int i=last;i <= n;i++)
	{
		path[u]=i;
		dfs(u+1,i+1);
	}
}
int main()
{
 	IOS;
	
	cin>>n;
	
	dfs(0,1);
		
 	return 0;
}

枚举位置,然后注意为了防止重复枚举,每次递归要记下上个位置放的数。

三.递归实现全排列型枚举

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
const int N=20;
bool st[N];
int path[N];
int n;

void dfs(int u)
{
	if(u >= n)
	{
		for(int i=0;i < n;i++) cout<<path[i]<<' ';
		cout<<endl;	
	}	
	
	for(int i=1;i <= n;i++)
	{
		if(!st[i])
		{
			path[u]=i;
			st[i]=true;
			dfs(u+1);
			st[i]=false;
		}
	}
}

int main()
{
 	IOS;
	
	cin>>n;
	
	dfs(0);
	 	
 	return 0;
}

也是枚举位置,但是注意它的数字的摆放不和组合型一样,其考虑了顺序。只要保证每个数字不会重复拜访即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值