[CareerCup 8.3] 求一个集合的所有子集

{}, {b}, {c}, {b, c}, {a}, {a, b}, {a, c}, {a, b, c}

/**

{}, {b}, {c}, {b, c}, {a}, {a, b}, {a, c}, {a, b, c}
**/
vector<set<int>> subset(set<int> s)
{
if (s.empty())
return vector<set<int>>();
int b = *s.begin();
s.erase(s.begin());
vector<set<int>> v = subset(s);
vector<set<int>> result;
set<int> t;
result.push_back(t);
t.insert(b);
result.push_back(t);
for (vector<set<int>>::iterator it = v.begin(); it != v.end(); it++)
{
if (! it->empty())
{
set<int> n(*it);
n.insert(b);
result.push_back(*it);
result.push_back(n);
}
}
return result;
}

0 000 {}
1 001 {a}
2 010 {b}
3 011 {a, b}
4 100 {c}
5 101 {a, c}
6 110 {b, c}
7 111 {a, b, c}

/**

0 000 {}
1 001 {a}
2 010 {b}
3 011 {a, b}
4 100 {c}
5 101 {a, c}
6 110 {b, c}
7 111 {a, b, c}
**/
vector<set<int>> subset_two(set<int> s)
{
int count = s.size();
int i, j;
vector<set<int>> v;
for (i = 0; i < 1 << count; i++)
{
set<int> t;
j = 0;
for (set<int>::iterator it = s.begin(); it != s.end(); it++)
{
if (get_bit(i, j++))
t.insert(*it);
}
v.push_back(t);
}
return v;
}

int main()
{
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
vector<set<int>> v = subset_two(s);
for (vector<set<int>>::iterator it = v.begin(); it != v.end(); it++)
{
for (set<int>::iterator sit = it->begin(); sit != it->end(); sit++)
cout << *sit << ' ';
cout << endl;
}
return 0;
}

posted on 2011-12-22 22:41  小橋流水  阅读(283)  评论(0编辑  收藏  举报