题目:
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], [] ]
代码如下:
void getsubset(vector<vector<int> > & result,vector<int> &S,int &i)
{
int n=S.size();
vector<int> tmp;
for(int j=0;j<n;j++)
{
if(i&(1<<j))
{
tmp.push_back(S[j]);
}
}
result.push_back(tmp);
}
vector<vector<int> > subsets(vector<int> &S)
{
int n=S.size();
sort(S.begin(),S.end());
vector<vector<int> > result;
for(int i=0;i<(1<<n);i++)
{
getsubset(result,S,i);
}
return result;
}