当前位置:网站首页>LeetCode 78:子集
LeetCode 78:子集
2022-07-06 06:55:00 【斯沃福德】
链接
题目:
思路:回溯(无重复元素不可复选)
回溯框架:

此题是形式一: 无重复元素不可复选,写回溯算法的时候,for就要从start开始,而不是从0开始! 即(2,1)和(1,2)是一个结果,故不能复选。
用start来保证每次递归时遍历数组后面未遍历到的数,而不会重复遍历前面的数
最后strat超过数组个数即为终止条件!
注意:
子集问题中,每个节点都是子集 !
需要在递归的【前序位置】将path添加到res !而不是到叶子节点才添加到res !
空集 [ ] 也算子集
Java实现:
class Solution {
List<List<Integer>> res=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
if(nums==null){
return new List<List<Integer>>;
}
dfs(nums,0);
return res;
}
void dfs(int[] nums,int start){
//用start来保证每次递归时遍历数组后面的数,而不会重复遍历前面的数,
//最后strat超过数组个数即为终止条件!
// 空集[]也算子集
res.add(new LinkedList(path)); // 每个节点都是子集 !而不是到叶子节点才添加到res !
for(int i=start;i<nums.length;i++){
//递归前选择
path.add(nums[i]);
//递归,i+1确保数组中元素不被重复使用
dfs(nums,i+1);
//递归后撤销
path.removeLast();
}
}
}
边栏推荐
- Arduino tutorial - Simon games
- [Yu Yue education] flower cultivation reference materials of Weifang Vocational College
- 接口自动化测试框架:Pytest+Allure+Excel
- 指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
- Short video, more and more boring?
- The difference between get and post request types
- [daily question] 729 My schedule I
- UWA Pipeline 2.2.1 版本更新说明
- Day 246/300 ssh连接提示“REMOTE HOST IDENTIFICATION HAS CHANGED! ”
- A brief introduction of reverseme in misc in the world of attack and defense
猜你喜欢
![[ 英语 ] 语法重塑 之 英语学习的核心框架 —— 英语兔学习笔记(1)](/img/02/41dcdcc6e8f12d76b9c1ef838af97d.png)
[ 英语 ] 语法重塑 之 英语学习的核心框架 —— 英语兔学习笔记(1)

Introduction to ros2 installation and basic knowledge

26岁从财务转行软件测试,4年沉淀我已经是25k的测开工程师...

AI on the cloud makes earth science research easier

Chapter 7 - thread pool of shared model

【软件测试进阶第1步】自动化测试基础知识
![[English] Verb Classification of grammatical reconstruction -- English rabbit learning notes (2)](/img/3c/c25e7cbef9be1860842e8981f72352.png)
[English] Verb Classification of grammatical reconstruction -- English rabbit learning notes (2)

医疗软件检测机构怎么找,一航软件测评是专家

【服务器数据恢复】IBM服务器raid5两块硬盘离线数据恢复案例

接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
随机推荐
Database basics exercise part 2
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
MySQL high frequency interview 20 questions, necessary (important)
Depth residual network
How to reconstruct the class explosion caused by m*n strategies?
UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
Basic commands of MySQL
BUU的MISC(不定时更新)
Do you really know the use of idea?
Suspended else
Fast target recognition based on pytorch and fast RCNN
软件测试外包到底要不要去?三年真实外包感受告诉你
成功解决TypeError: data type ‘category‘ not understood
Short video, more and more boring?
PCL realizes frame selection and clipping point cloud
[Yu Yue education] flower cultivation reference materials of Weifang Vocational College
PCL实现选框裁剪点云
Embed UE4 program into QT interface display
Simple query cost estimation
详解SQL中Groupings Sets 语句的功能和底层实现逻辑