题目描述
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],
[]
]
Solution 1
//AC版本
class Solution {
public:
void dfs(vector<vector<int> >&res,vector<int>ans,int val,int size,vector<int> &S)
{
if(val>=size) return ;
for(int i=val;i<size;++i)
{
ans.push_back(S[i]);
res.push_back(ans);
dfs(res,ans,i+1,size,S);
ans.pop_back();
}
return ;
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> >res;
sort(S.begin(),S.end());
res.push_back({});
vector<int>ans;
dfs(res,ans,0,S.size(),S);
for(int i=0;i<res.size()-1;++i)
for(int j=0;j<res.size()-i;++j)
if(res[j].size()>res[j+1].size())
swap(res[j],res[j+1]);
return res;
}
};
Solution 2
//顺序不对,不过也不失一种好办法
class Solution {
public:
vector<int> GetSub(int x,vector<int>&S)
{
vector<int>temp;
for(int i=1;i<=static_cast<int>(S.size());++i)
{
if(x&1) temp.push_back(S[i-1]);
x=x>>1;
}
return temp;
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> >res;
sort(S.begin(),S.end(),less<int>());
int MaxSize=1<<S.size();
for(int i=0;i<MaxSize;++i)
res.push_back(GetSub(i,S));
return res;
}
};