Leetcode 78 Subsets
2016-09-23 18:24
381 查看
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums =
求出给定集合的所有子集。
先贴上我的迭代深搜
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result(1);
for(int i=0;i<nums.size();i++)
{
int limit=result.size();
for(int j=0;j<limit;j++)
{
vector<int> temp=result[j];
temp.push_back(nums[i]);
result.push_back(temp);
}
}
return result;
}
};
DFS可以做,但是看到这题有更新颖的做法,
将集合中包含的数用二进制表示,1表示有,0表示没有,总共需要遍历2^n次。
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector< vector<int> > result;
sort(S.begin(), S.end());
// Loop from 0 to 2^n - 1
for (int x = 0; x < (1 << S.size()); ++x) {
vector<int> sln;
for (int i = 0; i < S.size(); ++i)
// If the i-th least significant bit is 1, then choose the i-th integer
if (x & (1 << i))
sln.push_back(S[i]);
result.push_back(sln);
}
return result;
}
};
Note: The solution set must not contain duplicate subsets.
For example,
If nums =
[1,2,3], a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
求出给定集合的所有子集。
先贴上我的迭代深搜
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result(1);
for(int i=0;i<nums.size();i++)
{
int limit=result.size();
for(int j=0;j<limit;j++)
{
vector<int> temp=result[j];
temp.push_back(nums[i]);
result.push_back(temp);
}
}
return result;
}
};
DFS可以做,但是看到这题有更新颖的做法,
将集合中包含的数用二进制表示,1表示有,0表示没有,总共需要遍历2^n次。
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector< vector<int> > result;
sort(S.begin(), S.end());
// Loop from 0 to 2^n - 1
for (int x = 0; x < (1 << S.size()); ++x) {
vector<int> sln;
for (int i = 0; i < S.size(); ++i)
// If the i-th least significant bit is 1, then choose the i-th integer
if (x & (1 << i))
sln.push_back(S[i]);
result.push_back(sln);
}
return result;
}
};
相关文章推荐
- 安卓常用模块收集(一)--编辑窗口
- 前端开发工具----WebStrom 2016.1破解
- ESRI2016用户大会资料
- Tomcat多域名的配置
- visual studio 2013设置背景图片
- Redis和硬盘数据库一起使用好吗?
- iOS 10 的一些变化
- 编译原理:短语,简单短语,句柄,语法树
- Android中RelativeLayout和LinearLayout性能分析
- 关于css伪类选择器
- 取distinct数据同时还取其他字段
- webview:net::ERR_CACHE_MISS错误
- [C#]委托和事件(详细讲解)
- 寻找和为Sum的多个数-2
- Linux命令(30):isof
- C++基础笔记之一:特殊字符的输入
- Tesseract-ocr在Visual Studio 2013中的配置和使用
- 【歌曲】花样年华
- paper 123: SVM如何避免过拟合
- Java中生成二维码图片