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 =
If S =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
typedef vector< int > vi;
typedef vector< vector<int> > vvi;
#define tr(c,it) for(decltype((c).begin()) (it) = (c).begin(); (it) != (c).end(); (it)++)
static bool vviCompare(vi a, vi b)
{
return (a.size()<b.size());
}
static bool viCompare(int a, int b)
{
return (a<b);
}
vector<vector<int> > subsets(vector<int> &S) {
vvi res;
int n = S.size();
int total = 1<<n;
for(int i = 0; i <total; i++)
{
vi v;
for (int j = 0; j<31; j++)
{
if(i & 1<<j)
{
v.push_back(S[j]);
}
}
res.push_back(v);
}
std::sort(res.begin(), res.end(), vviCompare);
tr(res, it)
{
std::sort((*it).begin(),(*it).end(), viCompare);
}
return res;
}
No comments:
Post a Comment