Print power set (DFS)
来源:互联网 发布:威海市南海新区知乎 编辑:程序博客网 时间:2024/06/14 20:45
今天无意间看到一道题,基本的数学组合题,但平常都不怎么注意,遂记录下来。
题目来源
题目描述
Print all combinations of a set. for example, there is an array {1, 2, 3}, its power set is:
{#}
{1} {2} {3}
{1, 2} {1, 3} {2, 3}
{1, 2, 3}
DFS解法
void DFS(vector<int>&vec, vector<vector<int>>& res, vector<int>& tmp, int len, int index) { if (index >= len) { res.push_back(tmp); return; } tmp.push_back(vec[index]); DFS(vec, res, tmp, len, index + 1); tmp.pop_back(); DFS(vec, res, tmp, len, index + 1);}vector<vector<int>> getPowerSet(vector<int>& vec) { vector<vector<int>> res; if (vec.empty()) return res; int len = vec.size(); vector<int> tmp; DFS(vec, res, tmp, len, 0); return res;}int main() { vector<int> vec = {1, 2, 3}; auto ans = getPowerSet(vec); for (auto &item : ans) { for (auto &num : item) cout << num << " " ; cout << endl; }}
BITMAP解法
void getPowerSet(vector<int>& vec) { int len = vec.size(); int total = 1 << len; for (int i = 0; i < total; ++i) { for (int j = 0; j < len; ++j) { if (i & (1 << j)) { // push_back or print cout << vec[j] << " "; } } cout << endl; }}
bitmap的思想在这道题上体现得淋漓尽致。值得好好回味。在以后的处理组合问题上,可以利用这种思想。
阅读全文
0 0
- Print power set (DFS)
- Power oj2470/DFS
- 8.4 Power Set
- EPI 5.5 THE POWER SET
- hdu4277 dfs+set
- hdu4277 DFS+SET
- hdu5355Cake(dfs+set)
- HDU5927 Auxiliary Set(dfs)
- Codeforces842C dfs+set
- poj3134 Power Calculus---迭代加深dfs
- 78. Subsets&集合的子集&Power Set
- hdu 1307(dfs+map+set)
- hdu4277 dfs+set判重
- bzoj3991 寻宝游戏 dfs&set
- hdu 5927 Auxiliary Set dfs
- Auxiliary Set----DFS思维题
- Auxiliary Set hdu5927(dfs)
- hdu 5927 Auxiliary Set (dfs)
- 基于Maven的Sonar安装配置
- 安卓自定义属性的使用
- HDU 2550 百步穿杨
- Unity中JSON序列化与反序列化
- Qt把控件截图并保存到剪切板、保存到图片文件
- Print power set (DFS)
- 怎样让mt_rand产生负数和正数
- 关于PL/SQL与Oracle 12c client的…
- 关于PL/SQL与Oracle Database 12c …
- Response.StatusCode的HTTP…
- 拆解VCM音圈马达,原理、结构
- [Python3爬虫从入门到精通]中国大…
- Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
- HDU5478Can you find it(快速幂)