| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 861 人关注过本帖
标题:前天下载的100题C经典,有些不懂...大家讨论下...
只看楼主 加入收藏
PcrazyC
Rank: 6Rank: 6
等 级:贵宾
威 望:29
帖 子:5652
专家分:0
注 册:2006-10-20
收藏
得分:0 

运行这个,根据数组的变化来推出作者的思想,算法我就不说了,自己考虑一下就出来了

#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);
}


雁无留踪之意,水无取影之心
2007-04-08 11:11
快速回复:前天下载的100题C经典,有些不懂...大家讨论下...
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019209 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved