主题:怎样用递归实现,列出一个集合的所有子集
#include <stdio.h>
#include <string.h>
void ListSubsets(char *set);
int main()
{
char set[80];
printf("Enter the elements of a set\n");
scanf("%s",set);
ListSubsets(set);
return 0;
}
void ListSubsets(char *set)
{
int i,j,n,m,k;
n=strlen(set);
m=1<<n;
/*To give a combination of a set,each element either belongs to it(1) or not belong in it(0).*/
/*Example:
C B A
empty set 0 0 0
A 0 0 1
B 0 1 0
AB 0 1 1
C 1 0 0
AC 1 0 1
BC 1 1 0
ABC 1 1 1
*/
for(i=0;i<m;i++)
{
putchar('{');
/*shift k left 1 bit,eg:1, 10, 100, ...*/
for(j=0,k=1;k<=i;k=k<<1,j++)
{
if(k&i) putchar(set[j]);
/*When the binary digit matches, print the correspondence element */
}
putchar('}');
putchar('\n');
}
}
全集里的每一个元素对应一个二进制位,
C B A
empty set 0 0 0
A 0 0 1
B 0 1 0
AB 0 1 1
C 1 0 0
AC 1 0 1
BC 1 1 0
ABC 1 1 1
如果用递归,该怎么办呢?
#include <string.h>
void ListSubsets(char *set);
int main()
{
char set[80];
printf("Enter the elements of a set\n");
scanf("%s",set);
ListSubsets(set);
return 0;
}
void ListSubsets(char *set)
{
int i,j,n,m,k;
n=strlen(set);
m=1<<n;
/*To give a combination of a set,each element either belongs to it(1) or not belong in it(0).*/
/*Example:
C B A
empty set 0 0 0
A 0 0 1
B 0 1 0
AB 0 1 1
C 1 0 0
AC 1 0 1
BC 1 1 0
ABC 1 1 1
*/
for(i=0;i<m;i++)
{
putchar('{');
/*shift k left 1 bit,eg:1, 10, 100, ...*/
for(j=0,k=1;k<=i;k=k<<1,j++)
{
if(k&i) putchar(set[j]);
/*When the binary digit matches, print the correspondence element */
}
putchar('}');
putchar('\n');
}
}
全集里的每一个元素对应一个二进制位,
C B A
empty set 0 0 0
A 0 0 1
B 0 1 0
AB 0 1 1
C 1 0 0
AC 1 0 1
BC 1 1 0
ABC 1 1 1
如果用递归,该怎么办呢?