关于有无重复的集合子集问题 这个帖子讲的很好很详细
下面是我的解法,使用的是第二种思路,排列组合的思想。
/**
集合中有多少个数,就用多少个位置表示,例如{2,5,8},则给出三位,这三位对应的1,表示取这个元素。相当于排列组合的思想
所以用0~2^n 来枚举所有可能情况
*/
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > ret;
int len = S.size();
int n = pow(2,len);
sort(S.begin(),S.end());
int idx;
vector<int> tmp;
for(int i = 0;i < n;i++){
idx = 0;
tmp.clear();
int p = i;
while(p){
if(p % 2)
tmp.push_back(S[idx]); //把S[]的第idx元素push进来
idx++;
p = p/2;
}
/* for(int j = 0;j<tmp.size();j++)
cout << tmp[j] << " ";
cout<<endl;
*/
ret.push_back(tmp);
}
//cout << ret.size() << endl;
return ret;
}
};
#include <set>
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
set<vector<int> > ret;
int len = S.size();
sort(S.begin(),S.end());
int n = pow(2,len);
int idx;
vector<int> tmp;
for(int i = 0;i < n;i++){
idx = 0;
tmp.clear();
int p = i;
while(p){
if(p % 2)
tmp.push_back(S[idx]); //把S[]的第idx元素push进来
idx++;
p = p/2;
}
ret.insert(tmp);
}
vector<vector <int> > real;
copy(ret.begin(), ret.end(), back_inserter(real));//这里需要注意,容器的copy函数
return real;
}
};
容器的copy函数
- template<class InputIterator, class OutputIterator>
- OutputIterator copy(
- InputIterator _First, //源容器起始位置
- InputIterator _Last, //源容器终止位置
- OutputIterator _DestBeg //目标容器的起始位置
- );
back_inserter 是iterator适配器,它使得元素被插入到作为实参的某种容器的尾部,如vector等http://www.cplusplus.com/reference/iterator/back_inserter/
上面是reference的介绍:
template <class Container> back_insert_iterator<Container> back_inserter (Container& x);
Construct back insert iterator
Constructs a
back-insert iterator that inserts new elements at the end of
x.
A
back-insert iterator
is a special type of
output iterator
designed to allow
algorithms
that usually overwrite elements (such as
copy
) to instead insert new elements automatically at the end of the container.
The type of x needs to have a push_back member function (such as the standard containers vector , deque and list ).
用法
std::copy (bar.begin(),bar.end(),back_inserter(foo));