运行这个,根据数组的变化来推出作者的思想,算法我就不说了,自己考虑一下就出来了
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 15
#define LOOP 1
void main(void) //求集全{1,2...n}的所有子集
{
char digit[MAXSIZE];
int i, j,k;
int n,sum=1; //sum=1是因为空集已经在循环前输出
printf("\nDirect Generation of All Subsets of a Set");
printf("\n=========================================");
printf("\n\nNumber of Elements in the Given Set --> ");
scanf("%d",&n);
if(n>15)
{
printf("the n is too large,it'll spare too much time\n");
return;
}
/* ---You'd better check to see if n is too large--- */
for (i = 0; i < n; i++) /* clear all digits to 0 */
digit[i] = '0';
printf("\n第一个子集合\t\t\t{}"); /* outpout empty set {} */
while (LOOP)
{
printf("\n数组元素:{");
for(k=0;k<n;k++)
printf("%c ",digit[k]);
printf("}");
for (i = 0; i < n && digit[i] == '1'; digit[i] = '0', i++)//找出第一个0的位置,第一次循环没用,但对 //以后的循环就有用了,因为数组变化了
; /* find first 0 position */
if(i==n-1)
printf("\n第%d次循环第一个0的位置:%d",sum,i-n+1);
else
printf("\n第%d次循环第一个0的位置:%d",sum,i);
if (i == n) /* if none, all pos. are 1 */
break; /* thus all elem. are in set*/
else
digit[i] = '1';/* now add one to this pos */
printf("\n数组元素:{");
for(k=0;k<n;k++)
printf("%c ",digit[k]);
printf("}");
for (i = 0; i < n && digit[i] == '0'; i++)
; /* find first 1 position */
printf("\n第%d次循环第一次1的位置:%d",sum,i);
printf("\n\n第%d个子集合\t\t\t{%d",sum+1,i+1); /* show its numner and */
for (j = i + 1; j < n; j++) /* others */
if (digit[j] == '1') //和digit[j]=='1'一样,因为只有1和0两个可能
printf(",%d", j + 1);
printf("}");
sum++;
}
printf("\n%d\n",sum);
}
雁无留踪之意,水无取影之心