算法基础篇(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;
}
相关推荐
阿昭L21 分钟前
堆结构与堆排序
数据结构·算法
2***574223 分钟前
人工智能在智能投顾中的算法
人工智能·算法
草莓熊Lotso27 分钟前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--01.第N个泰波拉契数,02.三步问题
开发语言·c++·经验分享·笔记·其他·算法·动态规划
mit6.8247 小时前
bfs|栈
算法
CoderYanger8 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz8 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
稚辉君.MCA_P8_Java8 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*8 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z10 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong34510 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法