class Solution {
//get the current whole set by expanding previous whole set
//for each element, do one expansion
public:
vector<vector<int> > subsets(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(S.begin(), S.end());
vector<vector<int>> ansSet(1);
for (int i = 0; i < S.size(); ++i)
{
int setSize = ansSet.size();
while (setSize-- > 0)
{
ansSet.push_back(ansSet[setSize]);
ansSet.back().push_back(S[i]);//...
}
}
return ansSet;
}
};
second time
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(S.begin(), S.end());
vector<vector<int> > sets(1, vector<int>());
for(int i = 0; i < S.size(); ++i)
{
int oldEnd = sets.size();
for(int j = 0; j < oldEnd; ++j)
{
vector<int> tmp = sets[j];
tmp.push_back(S[i]);
sets.push_back(tmp);
}
}
return sets;
}
};
本文介绍了一种使用C++实现的子集生成算法。该算法通过对输入整数集合进行排序,并通过迭代的方式生成所有可能的子集组合。文中提供了两种不同的实现方式,包括如何通过扩展现有集合来创建新的子集。
633

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



