今天上完数据结构课后
对于二叉树思想在某些问题上的恰到好处的运用感到amazing
记录一个印象最深刻的例子
利用二叉树实现幂集
在离散数学中我们知道
若一个集合中包含n个元素
则此集合的所有子集的个数和为
恰好是一颗满二叉树的叶子结点的个数
(偷一张老师的图来做笔记)
核心代码
template<class T>
void printPowerSet(vector<T>& set, vector<T>& ans, int pos) {
if (pos == set.size()) {
printVector(ans);
return;
}
ans.push_back(set[pos]);
printPowerSet(set, ans, pos + 1);
ans.pop_back();
printPowerSet(set, ans, pos + 1);
}
完整代码
#include<bits/stdc++.h>
using namespace std;
template<class T>
void printVector(vector<T>& set) {
for (auto it : set) {
cout << it << " ";
}
cout << endl;
}
template<class T>
void printPowerSet(vector<T>& set, vector<T>& ans, int pos) {
if (pos == set.size()) {
printVector(ans);
return;
}
ans.push_back(set[pos]);
printPowerSet(set, ans, pos + 1);
ans.pop_back();
printPowerSet(set, ans, pos + 1);
}
template<class T>
void printPowerSet(vector<T>& set) {
vector<T>ans;
printPowerSet(set, ans, 0);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
vector<char>set;
set.push_back('A');
set.push_back('B');
set.push_back('C');
set.push_back('D');
printPowerSet(set);
return 0;
}
运行结果截图