前言
本系列是我学习完大佬的方法后,为了蓝桥杯前几天可以快速过一遍所做,所以部分内容会很简洁。如果能够帮助到你,我也会很开心!!!
组合型枚举
题意中有从n中选择m个进行选择。即可考虑组合型枚举
#include<bits/stdc++.h>
using namespace std;
int n;//从n中选m个数
int m;
vector<int> chosen;
string s[1000];
void calc(int x) {
if (chosen.size() > m || chosen.size() + (n - x + 1) < m) //如果已选择的加上未选择的不足m
return;
if (x == n + 1)
{
for (int i = 0; i < chosen.size(); i++)
cout << s[chosen[i]] << " ";
puts("");
return;
}
chosen.push_back(x);
calc(x + 1);
chosen.pop_back();
calc(x + 1);
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> s[i];
}
calc(1);
}
排列型枚举
题意中有从n个中选择n个,并且在乎顺序的就可以考虑排列型枚举
#include <iostream>
#include <vector>
using namespace std;
int n;//n个数
vector<string> name;
int order[20];
bool chosen[20];
void calc(int k)
{
if (k == n + 1)//如果超过了就开始输出
{
for (int i =1; i <=n; i++)
cout << name[order[i]-1] << " ";//order[i] - 1的原因是因为name是从0开始索引的,而order是从1开始索引的
puts("");
return;
}
for (int i = 1; i <= n; i++)
{
if (chosen[i])
continue;
order[k] = i;//添加到排列中
chosen[i] = 1;//标记为已选
calc(k + 1);//
chosen[i] = 0;//标记为未选
order[k] = 0;
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
string s;
cin >> s;
name.push_back(s);
}
calc(1);
}
指数型枚举
给定一个数n,要求输出1~n所有可能的结果
#include <iostream>
using namespace std;
const int N = 20; //这里题目告诉n <= 15
bool select[N]; //false不选 true代表选
int n;
void dfs(int k)
{
if (k>n) //输出条件
{
for (int i = 1; i <= n; ++i)
{
if (select[i]) cout << i <<" ";
}
puts(""); //回车
return;
}
//有两种情况 选或者不选
select[k] = false;
dfs(k + 1);
select[k] = true;
dfs(k + 1);
}
int main()
{
cin >> n;//输入数n
dfs(1);//进入函数dfs
return 0;
}