搜索:
搜索的思想按照在状态空间中尝试的顺序分为多种。搜索看起来简单,但是往往是很多复杂的题目中必不可少的模块。
核心思路:
找到解空间,从解空间里面利用堆栈或队列求解,若解空间过大,则需要对其进行剪枝(优化)等操作。
练习:分别实现:
指数型枚举、组合型枚举、排列型枚举
指数型枚举
//指数型枚举求{1,2,3,4}的子集
#include <bits/stdc++.h>
using namespace std;
int n;
int arr[20];
void dfs(int cur, int m) //cur 代表当前层数 m代表选的数的个数
{
if(cur == n + 1) {
for(int i = 1; i < m; ++i) cout << arr[i] << " ";
puts("");
return;
}
dfs(cur + 1, m); //不选,仍为m个数
arr[m] = cur; //选第cur个数
dfs(cur + 1, m + 1);
arr[m] = 0; //回溯,但没有必要
}
int main()
{
cin >> n;
dfs(