subsets:非递归版本
yinlinglin opened this issue · 2 comments
yinlinglin commented
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
int size = S.size();
vector<vector<int>> result;
if(size==0) return result;
sort(S.begin(),S.end());
vector<int>v;
result.push_back(v);
for(int i=1;i<=size;i++)
{
int*p = new int[i];
p[0]=0;
int index = 0;
while(1)
{
if(p[index] == size)
{
if(index==0)break;
index--;
p[index]++;
}
else if(index == i-1)
{
v.clear();
for(int j = 0;j<i;j++)
v.push_back(S[p[j]]);
result.push_back(v);
p[index]++;
}
else
{
index++;
p[index]=p[index-1]+1;
}
}
delete[]p;
p =NULL;
}
return result;
}
};
yinlinglin commented
嘿嘿 写了个非递归的版本 供大神参考
AnnieKim commented
Good job!
看了你的标题,我也尝试自己写一个非递归版的subset,可是真难写,纠结了很久。
最后拿我的版本和你的版本对比了一下,发现还是你的if-else逻辑更有条理。
btw,在贴代码的时候可以用markdown格式哦,前后各用“```”包起来就可以了,这样就有缩进啦~
我整理一下代码update一下我的code:)
Thanks!