当前位置:网站首页>递归实现指数型枚举
递归实现指数型枚举
2022-07-13 18:06:00 【偷完面具就瞎跑】
递归实现指数型枚举
1、题目内容
从 1∼n 这 n 个整数中随机选取任意多个,输出所有可能的选择方案。
2、输入格式
输入一个整数 n。
3、输出格式
每行输出一种方案。
同一行内的数必须升序排列,相邻两个数用恰好 1 个空格隔开。
对于没有选任何数的方案,输出空行。
本题有自定义校验器(SPJ),各行(不同方案)之间的顺序任意。
4、数据范围
1≤n≤15
5、输入样例
3
6、输出样例
3
2
2 3
1
1 3
1 2
1 2 3
7、分析
二叉搜索树思想
每个数被选取的状态可以采用数组或者位运算来进行记录
解题思路:从前往后依次枚举每个数,每个数选与不选分别会走在两个分支里去,最终二叉搜索树(递归搜索树)的叶子节点就是最终的方案,中间节点都有两个选择即选与不选。
8、代码实现
#include<iostream>
using namespace std;
int n;
void dfs(int u,int state){
//记录状态可以用数组来记录,也可以使用位运算来记录,此题采用位运算来记录
if(u == n){
for(int i=0; i<n; i++)
if(state>>i & 1) //判断state的第i位是否为1
//注:怎么判断state的第i位是否为1,就把state右移i位再与1
cout<<i+1<<' ';
cout<<endl;
return;
}
dfs(u+1, state); //该数不用
dfs(u+1, state | 1<<u); //把state的第u个位置成1
}
int main(){
cin>>n;
dfs(0,0);
return 0;
}
9、递归思想
递归 思想 —— 从后往前算,就是把当前问题划归成几个简单的子问题,然后分别处理完每个子问题,最后再将子问题的解进行整合。
边栏推荐
- Network cabling overview
- 数制转换与子网划分
- Edge calculation kubeedge+edgemash
- Transaction module development
- Generally speaking, cookies, sessions, and tokens are different
- MATPLOTLIB—fail to allocate bitmap
- Basic principle and configuration of switch
- select / poll / epoll 讲解
- Dynamic programming + combinatorial mathematics
- LVM与磁盘配额
猜你喜欢

字节测试总监熬夜10天肝出来的测试岗面试秘籍,给你的大厂梦插上翅膀~

Network layer protocol

TCP protocol details

從功能測試到自動化測試,實現薪資翻倍,我整理的超全學習指南【附學習筆記】

【LeetCode】1217. Play chips

After 3 months of job hunting, most resumes are dead in the sea. When it comes to manual testing, they shake their heads again and again ~ it's too difficult

从软件测试培训班出来之后找工作的经历,教会了我这五件事...

POI framework learning - Import and export cases

“挤破脑袋进的腾讯,你凭什么要辞职?”

"Why do you want to resign, Tencent, which broke its head?"
随机推荐
The core difference between fairness and unfairness of reentrantlock
How to solve the relationship between the two use cases?
Pytest系列-01-安装与入门
Redis只能做缓存?太out了!
Setting the login interface in JMeter can only be called once
三层交换与VRRP
如何将 @Transactional 事务注解运用到炉火纯青?
主从复制读写分离保姆级教学
appium中desired_caps参数记录
File management - Alibaba cloud OSS learning (I)
MySQL lock mechanism
数制转换与子网划分
VLAN和Trunnk
传输层协议
交换机基本原理与配置
软件测试如何自学?【从0到1超全面解析】(附学习笔记)
2021/12/12 attack and defense world crypto question making record
Seckill activity development
After 3 months of job hunting, most resumes are dead in the sea. When it comes to manual testing, they shake their heads again and again ~ it's too difficult
Pytest series-01-installation and introduction