大清早,打开电脑,做点什么呢?还是忍不住到csdn来看看,这两天继续研究数据结构的递归与非递归。现在把昨晚写完的输出集合{1,2,...n}的幂集的非递归算法实现代码贴出来和大家分享一下吧,如果您有什么意见欢迎发送Email:yijiyong100@163.com 。
递归转非递归的方法大致分为两类:
1、分析原始的堆栈情况,自己设定一个堆栈来实现相关的进栈和出栈操作,比如二叉树的遍历算法从递归转到非递归(可以查看相关数据结构的书籍)。
2、根据递归的调用和输出的形式,找到其中的固有规律,设定循环和逻辑控制语句就可以实现非递归,通常情况下非递归的可控制性和执行时间都会优于递归。
这篇文章是关于输出集合{1,2,...n}的幂集的非递归的实现,至于递归实现大家可以参看:http://blog.csdn.net/yijiyong100/archive/2008/10/17/3093094.aspx
/****************************************/
/*Description: Implementation of none recursion*/
/*Print all the power set of n element*/
/*Email:yijiyong100@163.com*/
/*Author:yi_landry Harbin Normal University Computer Science*/
/*Date:2008-10-18*/
/*Copyright:HNU2008.cop*/
/*Environment:turbo c 2.01 English Version*/
/****************************************/
# include<stdlib.h>
# include<stdio.h>
# define OVERFLOW 0
static int ArraySize = 5;
/***************************************/
/*Judge the loop is over or not*/
/***************************************/
int isover(int * a,int len)
{
int i;
len = ArraySize;
for(i=0;i<len;i++)
if (a[i] == 0) return 0;
return 1;
}
/***************************************/
/*the core function of this program*/
/***************************************/
Powerset(int * a,int len)
{
int count = 0;
int * guide= (int *)malloc((len+1)*sizeof(int));
int i,j,pos=len-1,pos1;
len = ArraySize;
for(i=0;i<len;i++)
guide[i]=0;
guide[len]=1;
while(!isover(guide,len))
{
printf(" { ");
for(j=0;j<len;j++)
{
if(j>=pos)
guide[j]=(guide[j]!=guide[j+1]);/*the core code ,the last zero in the guide (include the element after it),the value*/
/*is the original value exclusive or with the value of the next element*/
if(guide[j]==0)
pos1=j;
else
printf(" %d ",a[j]);
}
printf(" } ");
printf("/n");
pos=pos1;
count++;
}
if (isover(guide,len))
{
count++;
printf(" { } /n");
}
printf("The total element in the powerset is %d /n",count);
}
/***************************************/
/*Just a example function*/
/***************************************/
Example()
{
int i;
int * A = (int *)malloc(ArraySize*sizeof(int));
int * c = A;
for (i = 0;i<ArraySize;i++)
{
* c = i + 1;
c++;
}
Powerset(A,ArraySize);
}
/***************************************/
/*The main part of this program*/
/***************************************/
main()
{
int size;
while(1)
{
printf("Please input the size of the array,we will output the powerset. if you want to exit,you can enter -1 !/n");
scanf("%d",&size);
if (size == -1) break;
ArraySize = size;
Example();
}
}