#include <fstream>
#include <iostream>
#include <string>
#define N 6 //集合中元素的个数 元素为 1...N
using namespace std;
void WriteToFile(const char s[], const char fileName[])
{
// 创建一个ofstream对象并打开一个文件
ofstream fileOut(fileName,ios::app);
if (fileOut.is_open()) {
// 将数据写入文件
fileOut << s;
// 关闭文件
fileOut.close();
}
return ;
}
void dfs(int depth,string s,int pos,int n)
{
if (pos==n*2)
{
WriteToFile("{", "content.txt");
WriteToFile(s.c_str(), "content.txt");
WriteToFile("}\n", "content.txt");
cout <<"{" << s <<"}" << endl;
return;
}
if (depth >= N)
{
return;
}
dfs(depth + 1, s,pos,n);
s[pos] = '1' + depth;
if(pos < 2*n-2 )
s[pos + 1] = ',';//偶数位为集合元素,奇数位为','
dfs(depth + 1, s,pos+2,n);
}
int main() {
cout << "{}" << endl;//空集情况
WriteToFile("{}\n", "content.txt");
for (int i = 1; i <= N; i++)
{
string s(i * 2 - 1, '0');
dfs(0, s, 0, i);
}
return 0;
}
输出1到N 的子集并并保存到文件
于 2024-04-19 13:58:25 首次发布