Files
python/TangDou/AcWing/BeiBao/487_Prepare.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

50 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
vector<string> a = {"1"};
vector<string> b = {"2", "3", "4"};
void dfs(int u, string s) {
if (u == 3) {
cout << s << " ";
return;
}
dfs(u + 1, s);
dfs(u + 1, s + "," + b[u]);
}
// 生成分组信息
int main() {
// ①二进制枚举法【正规方法】
// 因为手动录入了第一个元素,所以这里枚举避开了全不选的0
int sz = b.size();
for (int i = 1; i < 1 << sz; i++) { // 1~2^3.模拟每个数
string t = a[0];
for (int j = 0; j < sz; j++) // 每个数位
if (i >> j & 1) // 如果此位置为1,表示当前数字出现在组合中
t = t + "," + b[j];
a.push_back(t);
}
for (auto c : a) cout << c << " ";
puts("");
// ② dfs【一般推荐】
dfs(0, a[0]);
puts("");
// ③ 多次循环法【不推荐】
a = {"1"};
b = {"2", "3", "4"};
for (int i = 0; i < b.size(); i++) {
sz = a.size();
for (int j = 0; j < sz; j++)
a.push_back(a[j] + "," + b[i]);
}
for (auto c : a) cout << c << " ";
// 清空再来
puts("");
return 0;
}