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], [] ]
S先排序下,使全集能够按顺序输出。
class Solution {
public:
vector<vector<int> >re;
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(),S.end());
for(int i = 0 ; i <= S.size() ; i++)
{
find(S , i);
}
return re;
}
void find(vector<int> ve,int k)
{
vector<int> result;
if(k == 0)
{
re.push_back(result);
return;
}
if(k == ve.size())
{
re.push_back(ve);
return;
}
get(ve,-1,k,result);
}
void get(vector<int> ve,int begin,int k,vector<int> result)
{
if(begin >= 0)
{
result.push_back(ve[begin]);
}
if(k == 0)
{
sort(result.begin(),result.end());
re.push_back(result);
return;
}
for(int i = begin+1; i <= ve.size() - k ; i++)
{
get(ve,i,k-1,result);
}
}
};
有更简单的做法,维护一个index。当index到尾部是则将集合返回。
看到一个更漂亮的做法,忍不住贴过来。源自http://www.cppblog.com/Uriel/articles/205467.html
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > res;
sort(S.begin(), S.end());
for(int i = 0; i < (1 << S.size()); ++i) {
vector<int> tp;
for(int j = 0; j < S.size(); ++j) {
if((1 << j) & i) tp.push_back(S[j]);
}
res.push_back(tp);
}
return res;
}
};
posted on 2014-03-14 09:42 pengyu2003 阅读(131) 评论(0) 收藏 举报
浙公网安备 33010602011771号