您的位置:首页 > 其它

[leetcode] Subsets

2015-01-06 17:21 260 查看

Subsets

Given a set of distinct integers, S, 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 S =
[1,2,3]
, a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

思路:

dfs。原容器中的元素在子集中有两种可能,要么在要么不在。因此肯定在一个函数中有两个递归的过程,一个是不放数据,一个是放数据。如此一直递归,直到原容器的大小时递归结束。

题解:

vector<vector<int> > subsets(vector<int> &S) {
vector <int> temp;
vector<vector<int> >ans;
ans.push_back(temp);   //Enters null set
int len=S.size();
int len2;
if(len==0)
return ans;

sort(S.begin(),S.end());

for(int i=0 ; i<len ; i++)   //Traverses the whole input array
{
len2=ans.size();
// Since we cannot append the new number along with the null set therefore this is done outside the loop
temp.clear();
temp.push_back(S[i]);
ans.push_back(temp);

for(int j=1 ; j<len2 ; j++)
{
vector<int> temp2(ans[j]);
temp2.push_back(S[i]);
ans.push_back(temp2);
}
}
return ans;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: