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:
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
int len = S.size();
vector<vector<int>> result;
int maxNum = pow(2, len);
for(int i = 0; i < maxNum; i++)
{
vector<int> temp;
for(int j = 0; j < len; j++)
{
if(i & (1<<j))
temp.push_back(S[j]);
}
result.push_back(temp);
}
return result;
}
};
Solution 2:
class Solution {
public:
vector<vector<int>> result;
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
result.clear();
vector<int> temp;
generate(S, temp, 0);
return result;
}
void generate(vector<int> &S, vector<int> temp, int level)
{
if(level == S.size())
{
result.push_back(temp);
return;
}
generate(S, temp, level+1);
temp.push_back(S[level]);
generate(S, temp, level+1);
}
};