递归版本:先拿走一个元素,找到剩下元素的所有子集,它们也是所有元素的自己;然后将拿掉元素加回去,也是所有元素的子集
最后需要对元素排序保持有序的要求。
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
return _subsets( S, 0);
}
vector< vector< int> > _subsets( vector< int> &nums, int index){
vector< vector< int> > res;
if( index == nums.size())
return vector< vector< int> >( 1, vector< int>());
else{
vector< vector< int> > tmp = _subsets( nums, index+1);
int val = nums[index];
for( int i = 0; i < tmp.size(); ++i){
vector< int> subset = tmp[i];
res.push_back( subset);
subset.push_back(val);
res.push_back( subset);
}
}
for( int i = 0; i < res.size(); ++i){
sort( res[i].begin(), res[i].end());
}
sort( res.begin(), res.end());
return res;
}
};
迭代版:3个元素的子集有2^3个,所以,从二进制0到7,如果二进制位为1就把对应下标元素推入,不然就跳过,比如1,2l两个元素00对应{},01对应{1},10对应{2},11对应{1,2},最后还是得对结果排序
如果元素个数大于size_t的最大位数就不行了,还是得用递归。
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector< vector< int> > res;
size_t upper_bounds = 1 << S.size();
for( size_t i = 0; i < upper_bounds; ++i){
vector< int> tmp;
size_t index = 0;
size_t j = i;
while(j){
if( j & 1)
tmp.push_back(S[index]);
j >>= 1;
++index;
}
res.push_back(tmp);
}
for( int i = 0; i < res.size(); ++i)
sort( res[i].begin(), res[i].end());
sort( res.begin(), res.end());
return res;
}
};