算法基础篇(10)递归型枚举与回溯剪枝

搜索,是一种枚举,通过穷举所有情况来找到最优解或者统计合法解的个数。搜索一般分为深度优先搜索 (DFS)与 宽度优先搜索(BFS)

回溯:在搜索过程中,遇到走不通或者走到底的情况,就回头

剪枝:剪掉在搜索过程中重复出现或者不是最优解的分支

1、枚举子集

cpp 复制代码
#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;

int n;
string path; //记录递归过程中,每一步的决策

void dfs(int pos)
{
	if (pos > n)
	{
		//path存着前n个人的决策
		cout << path << endl;
		return;
	}

	//不选
	path += "N";
	dfs(pos + 1);
	path.pop_back(); //回溯,清空现场

	//选
	path += "Y";
	dfs(pos + 1);
	path.pop_back();
}

int main()
{
	cin >> n;

	dfs(1);

	return 0;
}

1.2 组合型枚举

cpp 复制代码
#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
using namespace std;

int n, m;
vector<int> path;

void dfs(int begin)
{
	if (path.size() == m)
	{
		for (auto e : path)
			cout << e << " ";

		cout << endl;
		return;
	}

	for (int i = begin;i <= n;i++)
	{
		path.push_back(i);
		dfs(i + 1);
		path.pop_back();
	}
}

int main()
{
	cin >> n >> m;

	dfs(1);

	return 0;
}

1.3 枚举排列

cpp 复制代码
#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
using namespace std;

int n, k;
vector<int> path;

const int N = 20;
bool st[N];

void dfs()
{
	if (path.size() == k)
	{
		for (auto e : path)
			cout << e << " ";

		cout << endl;
		return;
	}

	for (int i = 1;i <= n;i++)
	{
		if (st[i])
			continue;
		
		path.push_back(i);
		st[i] = true;					
		dfs();

		//恢复现场
		st[i] = false;
		path.pop_back();
	}
}

int main()
{
	cin >> n >> k;

	dfs();

	return 0;
}

1.4 全排列

cpp 复制代码
#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

int n;
vector<int> path;

const int N = 10;
bool st[N];

void dfs()
{
	if (path.size() == n)
	{
		for (auto e : path)
		{
			printf("%5d", e);
		}
		cout << endl;
		return;
	}
		
	for (int i = 1;i <= n;i++)
	{
		if (st[i])
			continue;

		path.push_back(i);
		st[i] = true;
		dfs();

		path.pop_back();
		st[i] = false;
	}
	
}

int main()
{
	cin >> n;

	dfs();

	return 0;
}
相关推荐
想吃火锅10056 小时前
【leetcode】88.合并两个有序数组js
算法
生成论实验室6 小时前
机器人:一个自主运动的系统
人工智能·算法·语言模型·机器人·自动驾驶·agi·安全架构
Qres8216 小时前
算法复键——树状数组
数据结构·算法
H178535090966 小时前
SolidWorks第四部分_直接实体建模特征9_替换面原理
线性代数·算法·机器学习·3d建模·solidworks
不会就选b6 小时前
算法日常・每日刷题--<二分查找>3
算法
绿算技术7 小时前
Mooncake 与绿算ForinnBase GroundPool如何联手打破推理僵局?
科技·算法·架构
-森屿安年-7 小时前
63. 不同路径 II
c++·算法·动态规划
老余捞鱼8 小时前
线性回归实战:5步验证你的量化因子是否真有效
算法·金融·回归·线性回归·ai量化
想吃火锅10058 小时前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
码云数智-大飞8 小时前
RAII 与智能指针深度拆解
java·前端·算法