这是我刚开始想得,我觉得用归并得递归版也是可以解得;
将每一个左边都加入,然后,将其备份一份,然后将右边得每一个都与左边得每一个合并,然后在加入,然后给出一个总得,返回;
这个方法是work得,但是可想而知,由于系统压栈得原因,直接导致栈溢出;我试着用自底向上得归并去做,发现并不行,其数据得结构就变了;于是我只能想一个新得算法
这是归并得算法:
class S1olution {
public:
vector<vector<int>> merge(vector<int>& nums, int lo, int hi)
{
if (lo == hi)
{
vector<int> temp;
temp.push_back(nums[lo]);
vector<vector<int>> res;
res.push_back(temp);
return res;
}
int mi = lo + ((lo + hi) >> 1);
vector<vector<int>> left = merge(nums, lo, mi);
vector<vector<int>> right = merge(nums, mi + 1, hi);
vector<vector<int>> RES;
RES=left;
for (auto it : right)
{
RES.push_back(it);
}
for (vector<vector<int>>::iterator lf= left.begin();lf!=left.end();++lf)
{
for (vector<vector<int>>::iterator ri = right.begin(); ri != right.end(); ++ri)
{
vector<int> it = *ri;
for (vector<int>::iterator var=it.begin();var!=it.end();++var)
{
lf->push_back(*var);
}
}
}
for (auto lf : left)
{
RES.push_back(lf);
}
return RES;
}
vector<vector<int>> subsets(vector<int>& nums) {
if (nums.size() == 0)
{
vector<vector<int>> res;
return res;
}
vector<vector<int>> res = merge(nums, 0, nums.size() - 1);
vector<int> none;
res.push_back(none);
return res;
}
};
这是我重新想得算法:
其实就是每遍历一个数,就将其加入,然后把之前得副本加入这个数再加入一遍,
还挺快得,超过95%,哈哈
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>> res, int cur)
{
vector<vector<int>> RES=res;
vector<int> CUR;
CUR.push_back(cur);
RES.push_back(CUR);
for (vector<vector<int>>::iterator lf= res.begin();lf!=res.end();++lf)
{
vector<int> &it = *lf;
it.push_back(cur);
}
for (auto lf : res)
{
RES.push_back(lf);
}
return RES;
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
if (nums.size() == 0)
{
return res;
}
for(auto it:nums)
{
res=merge(res,it);
}
vector<int> none;
res.push_back(none);
return res;
}
};