求集合A的子集
1.什么是子集
子集是一个数学概念:如果集合A的任意一个元素都是集合B的元素,那么集合A称为集合B的子集。
符号语言:若∀a∈A,均有a∈B,则A⊆B。
2.求解子集的步骤(以123为例)
从深度优先搜索的角度观察:
2.1代码
#include <iostream>
#include <vector>
using namespace std;
/*
求a的子集
*/
void subset(vector<int> &nums, vector<int>& tag, int i, int n)
{
if (i == n)
{
for (int j = 0; j < n; ++j)
{
if (tag[j] == 1)
{
cout << nums.at(j);
}
}
cout << endl;
return;
}
else
{
tag[i] = 1;
subset(nums, tag, i + 1, n);
tag[i] = 0;
subset(nums, tag, i + 1, n);
}
}
int main()
{
vector<int> ar{ 1,2,3 };
vector<int> tag{ 0,0,0 };
subset(ar, tag, 0, 3);
return 0;
}