跳到正文

个人记录

搜索

smallycat约 5 分钟
原文

这是 2026年4月24日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年4月24日
收录
2026年4月24日
更新
2026年11月10日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

搜索

- 枚举元组:

定义:
枚举k元组
做法:
递归k层,每层[1,n]
题目:
B3621 枚举元组
代码(注释版):

C++
#include<bits/stdc++.h>  
using namespace std;
int n, k;
int a[15];
void dfs(int x){
	if(x == n + 1){//第x层还没选呢! 
		for(int i = 1; i <= n; i++){
			cout << a[i] << " "; 
		}
		cout << endl;
		return ;//返回值没用了 多写会比不写占空间 
	}
	for(int i = 1; i <= k; i++){
		a[x] = i;
		dfs(x + 1);
	}
}
int main(){
	cin >> n >> k;
	dfs(1);
	return 0;
}

- 枚举子集:

定义:
枚举n个元素的集合的k元子集
做法:
递归枚举
题目:
B3622 枚举子集(递归实现指数型枚 举)
代码(注释版):
二进制版(1为y 0为n

C++
#include<bits/stdc++.h>
using namespace std;
int n, x;
void chai(int y){
	string a;
	for(int i = 1; i <= n; i++){
		if(y % 2 == 0)a += 'N';
		else a += 'Y';
		y /= 2; 
	}
	int z = a.length();
	for(int i = z - 1; i >= 0; i--){
		cout << a[i];
	}
	cout << endl;
}
int main(){ 
	cin >> n;
	x = (1 << n) - 1;//(减号优先级高)优先级问题!!!!!!!!!!!!!!! 
	for(int i = 0; i <= x; i++){
		chai(i);	
	}
	return 0;
}

超级普通的递归版本

C++
#include<bits/stdc++.h>  
using namespace std;
int n;
int a[15], vis[15];
void dfs(int x){
	if(x == n + 1){//第x层还没选呢! 
		for(int i = 1; i <= n; i++){
			if(a[i] == 1)cout <<"N";
			else cout << "Y";
		}
		cout << endl;
		return ;//返回值没用了 多写会比不写占空间 
	}
	for(int i = 1; i <= 2; i++){//只有两种可能N或者Y
		a[x] = i;
		dfs(x + 1);
	}
}
int main(){
	cin >> n;
	dfs(1);
	return 0;
}

- 枚举排列:

定义:
就是枚举排列的所有可能
做法:
递归k层,每层[1,n],用标记数组保证各个元素不重复
题目:
B3623 枚举排列(递归实现排列型枚举) 代码(注释版):

C++
#include<bits/stdc++.h>  
using namespace std;
int n, k;
int a[15], vis[15];
void dfs(int x){
	if(x == k + 1){
		for(int i = 1; i <= k; i++){
			cout << a[i] << " "; 
		}
		cout << endl;
		return ;
	}
	for(int i = 1; i <= n; i++){
		if(!vis[i]){
			a[x] = i;
			vis[i] = 1;
			dfs(x + 1);
			vis[i] = 0;
		}
	}
}
int main(){
	cin >> n >> k;
	dfs(1);
	return 0;
}

- 枚举组合:

定义:
就是枚举组合的所有可能
做法:
递归k层,每层[1,n],用标记数组保证各个元素不重复,保证前一个数比后一个数小
题目:
P10448 组合型枚举 代码(注释版):

C++
#include<bits/stdc++.h>  
using namespace std;
int n, k;
int a[100], vis[150];
void dfs(int x){
	if(x == k + 1){ 
		for(int i = 1; i <= k; i++){
			cout << a[i] << " "; 
		}
		cout << endl;
		return ;
	}
	for(int i = a[x - 1] + 1; i <= n; i++){//和枚举排列的区别在于第二次选数要比上次选的数大
		if(!vis[i]){
			a[x] = i;
			vis[i] = 1;
			dfs(x + 1);
			vis[i] = 0;
		}
	}
}
int main(){
	cin >> n >> k;
	dfs(1);
	return 0;
}