Leetcode#78 Subsets
有两种方法:
1. 对于序列S,其子集可以对应为一个二进制数,每一位对应集合中的某个数字,0代表不选,1代表选,比如S={1,2,3},则子集合就是3bit的所有二进制数。
所以,照着二进制位去构造解空间即可。
2. 也可以用DFS做,对于每个元素,要么选,要么不选。
记得先排序,因为结果集的数字要从小到大出现。
代码(DFS版本):
vector<vector<int> > res;
void dfs(vector<int> &S, vector<int> ans, int pos) {
if (pos == S.size()) {
res.push_back(ans);
return;
}
dfs(S, ans, pos + );
ans.push_back(S[pos]);
dfs(S, ans, pos + );
}
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
dfs(S, vector<int>(), );
return res;
}
Leetcode#78 Subsets的更多相关文章
- leetcode 78. Subsets 、90. Subsets II
第一题是输入数组的数值不相同,第二题是输入数组的数值有相同的值,第二题在第一题的基础上需要过滤掉那些相同的数值. level代表的是需要进行选择的数值的位置. 78. Subsets 错误解法: cl ...
- [LeetCode] 78. Subsets 子集合
Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be ...
- LeetCode 78. Subsets(子集合)
Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not ...
- LeetCode 78 Subsets (所有子集)
题目链接:https://leetcode.com/problems/subsets/#/description 给出一个数组,数组中的元素各不相同,找到该集合的所有子集(包括空集和本身) 举例说 ...
- [leetcode]78. Subsets数组子集
Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solut ...
- [LeetCode] 78. Subsets tag: backtracking
Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solut ...
- Leetcode 78. Subsets (backtracking) 90 subset
using prev class Solution { List<List<Integer>> res = new ArrayList<List<Integer&g ...
- leetCode 78.Subsets (子集) 解题思路和方法
Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must ...
- [LeetCode] 90.Subsets II tag: backtracking
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the ...
随机推荐
- Java学习之Java的单例模式
单例模式有一下特点: 1.单例类只能有一个实例.2.单例类必须自己自己创建自己的唯一实例.3.单例类必须给所有其他对象提供这一实例. 单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个 ...
- (转)文件系统缓存dirty_ratio与dirty_background_ratio两个参数区别
这两天在调优数据库性能的过程中需要降低操作系统文件Cache对数据库性能的影响,故调研了一些降低文件系统缓存大小的方法,其中一种是通过修改/proc/sys/vm/dirty_background_r ...
- upTodown
------->>> 从左图变为有图,并实现将左图上面的信息隐藏. <img src="../images/up.gif" border=&qu ...
- Linux 内存布局
本文主要简介在X86体系结构下和在ARM体系结构下,Linux内存布局的概况,力求简单明了,不过多深入概念,多以图示的方式来记忆理解,一图胜万言. Technorati 标签: 内存 布局 ...
- bzoj 1006: [HNOI2008]神奇的国度
这是个标准的弦图,但如果不知道弦图就惨了=_= 趁着这个机会了解了一下弦图,主要就是完美消除序列,求出了这个就可以根据序列进行贪心染色. 貌似这个序列很神,但是具体应用不了解…… 这道题为什么可以这么 ...
- C++ 嵌入汇编 获取CPU信息
#include "windows.h" #include "iostream" #include "string" using names ...
- 试写Python内建函数range()
还没查阅源码,先试着练手 class my_range(object): def __init__(self, *args): if not args: raise TypeError, 'range ...
- linux系统man查询命令等级与意义
代号 意义 1 可执行程序和一般shell命令 2 系统调用函数 3 库函数 4 设备配置文件,通常在/dev下 5 配置文件,/ec下 6 游戏 7 协议及杂项 8 管理员命令 9 与内核相关
- unity 3消 游戏
3消游戏跟着智能手机流行到现在已经有很长一段时间,unity实现的3消 https://github.com/textcube/match3action 截图如下: 在阅读源码的时候不难发现,Game ...
- NaN 和 Infinity
using Fasterflect; using System; using System.Collections.Generic; using System.Linq; using System.R ...