Therefore, all subgroups can be generated by changing the bool tag of each element.
For example, for a subgroup of three elements, a complete set means that all elements are in the subgroup, that is,11,only the first two are11,and only the last subgroup is 00 1.
Similarly, for any subgroup of multiple elements, all subgroups can be generated by changing the state of each element.
In the following algorithm, each bit of an integer variable is regarded as the existence sign of an element, that is, the third bit of 1 indicates that the third element is in this subgroup:
# include & ltstdio.h & gt
int main()
{
Unsigned iLen = 0;;
Puts ("The number of elements in a set? ( 1~3 1)");
scanf("%u ",& ampiLen);
if(iLen & gt; 3 1 | | iLen & lt; = 0)
{
Puts ("out of range");
return- 1;
}
FILE *pFile = fopen("out.txt "," w ");
if (pFile == NULL)
{
Puts ("Failed to open file");
return-2;
}
Unsigned IMAX =1< & ltiLen
For (unsigned I =1; I & ltiMax++i)
{
for(int j = 0; j & ltiLen++j)
{
If ((I>>j)&; 1)
{
fprintf(pFile," %u ",j+ 1);
}
}
fputc('\n ',pFile);
}
fclose(pFile);
}
In the above algorithm, when there are three elements, the first three bits are processed, and the integer range composed of three bits is 1~7 (empty set is not processed), so for each number of 1~7, take out each bit in turn and judge whether it is 1, and you can know whether the element corresponding to this bit is in the set.
such as
When I equals 5, 5 equals binary 10 1, 1 and 3 elements are in the set, and the second one is not, which is a subset.
The above code can only handle the elements of 1~3 1, mainly considering that there are too many elements to list them all (n! Excessive growth); If you have to list, you can increase the number by the same token. Large numbers range from 1 to n, and each number as a set is 1, indicating that this element is in the set.