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);
}
};

本文介绍两种生成给定整数集合所有可能子集的方法。方法一使用位操作遍历所有组合,确保子集按非递减顺序排列且无重复。方法二采用递归方式生成子集,通过深度优先搜索构建解空间。
633

被折叠的 条评论
为什么被折叠?



