[Leetcode]Subsets
2015-11-20 16:37
357 查看
Subsets My Submissions Question
Total Accepted: 72388 Total Submissions: 247343 Difficulty: Medium
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
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],
[]
]
Subscribe to see which companies asked this question
我是按照我博客里那种方法做的,有些地方不太一样,用adapter模式(允许我装个逼)搞一下,结果对顺序还有要求。。。干脆每次插入都排个序,这样时间就上去了,12ms。如果不排序就要修改一下getSubstring()这个就行,可是我懒得修改了。当然用DFS做也没问题,就比较简单了。下面把两种方法都贴出来
DFS:
Total Accepted: 72388 Total Submissions: 247343 Difficulty: Medium
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
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],
[]
]
Subscribe to see which companies asked this question
我是按照我博客里那种方法做的,有些地方不太一样,用adapter模式(允许我装个逼)搞一下,结果对顺序还有要求。。。干脆每次插入都排个序,这样时间就上去了,12ms。如果不排序就要修改一下getSubstring()这个就行,可是我懒得修改了。当然用DFS做也没问题,就比较简单了。下面把两种方法都贴出来
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { int len = nums.size(); string str; for(int i = 0;i != len;++i){ str.push_back(nums[i] + '0'); } vector<string> res = func(str); vector<vector<int> > ans; ans.push_back({}); for(int i = 0;i != res.size();++i){ vector<int> tem; for(int j = 0;j != res[i].size();++j){ tem.push_back(res[i][j] - '0'); } sort(tem.begin(),tem.end()); ans.push_back(tem); } sort(ans.begin(),ans.end()); return ans; } vector<string> func(string str){ int len = str.size(); vector<string> res; int num = 1 << len; num = num - 1; //cout << num << endl; for(int i = 1;i <= num;++i){ string tem = getSubstring(str,i); res.push_back(tem); } return res; } string getSubstring(string str,int num){ string tem; //cout << num << endl; int len = str.size(); int n = len - 1; while(num){ if(num & 0x1){ tem += str ; } num = num >> 1; --n; } return tem; } };
DFS:
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> res; vector<int> path; dfs(nums, 0, path, res); return res; } void dfs(vector<int>& nums, int index, vector<int>& path, vector<vector<int>>& res) { res.push_back(path); for (unsigned int i = index; i < nums.size(); i++) { path.push_back(nums[i]); dfs(nums, i+1, path, res); path.pop_back(); } } };
相关文章推荐
- Android Interface Definition Language (AIDL)
- 百度云资源提取链接
- Math.random() 得到6位随机数
- 使用Redis实现抢购的一种思路
- 通过代码添加约束之NSLayoutConstraint
- 5-2 派生类的构造函数
- hdu1010 Tempter of the Bone
- Yum安装svn服务器并搭建自己的svn项目
- Oracle查询表空间
- myeclipse building workspace如何禁止及提高myeclipse速度
- Android——简易进度条与对话框
- 产品经理 & 项目管理
- 二分法猜价格
- fastjson使用心得
- 最佳实践
- HTTP中的get和post的区别
- android-list底部按钮
- K3老单自定义字段自动折行显示
- PHP语法(一):基础和变量
- 程序自动分析