这两天又开始研究数据结构了,顺便写了个回溯的程序。贴出来和大家分享一下..... ,如果您有什么看法可以发送到yijiyong100@163.com ,欢迎您提出意见。
/****************************************/
/*Description: BackTrack*/
/*Print all the power set of n element*/
/*Email:yijiyong100@163.com*/
/*Author:yi_landry Harbin Normal University Computer Science*/
/*Date:2008-10-16*/
/*Copyright:HNU2008.cop*/
/*Environment:turbo c 2.01 English Version*/
/****************************************/
/***************************************/
/*Just for simple , we use an integer array instead of List*/
/***************************************/
# include<stdlib.h>
# include<stdio.h>
# define OVERFLOW 0
static int ArraySize = 3;
/***************************************/
/*Print the element of powerset*/
/***************************************/
void Output(int * a)
{
int i = 0;
char c = '{';
char d = '}';
printf("%c",c);
for (i=0;i<ArraySize;i++)
{
if (*a != -1) printf(" %d ",*a);
a++;
}
printf("%c",d);
printf("%c",'/n');
}
/***************************************/
/*Get the element at some location*/
/***************************************/
int GetElem(int * a,int position)
{
return *(a+position);
}
/***************************************/
/*Get the length of the array*/
/***************************************/
int ListLength(int * a)
{
int iNumber = 0,i = 0;
for (i=0;i<ArraySize;i++)
{
if (*a != -1) iNumber++;
a++;
}
return iNumber;
}
/***************************************/
/*Insert a new element at some location*/
/***************************************/
void ListInsert(int * a,int position,int n)
{
*(a+position) = n;
}
/***************************************/
/*Delete a element at some location*/
/***************************************/
void ListDelete(int * a,int position,int n)
{
if (*(a+position) == n)
*(a+position) = -1;
}
/***************************************/
/*Get the powerset,it's the core function of this program*/
/***************************************/
void GetPowerSet(int i,int * A,int * B)
{
int k = 0;
int x = -1;
if (i>=ListLength(A)) Output(B);
else {
x = GetElem(A,i);
k = ListLength(B);
ListInsert(B,k,x);
GetPowerSet(i+1,A,B);
ListDelete(B,k,x);
GetPowerSet(i+1,A,B);
}
}
/***************************************/
/*Get the powerset,it's the core function of this program*/
/***************************************/
void Example()
{
int * A = (int *)malloc(ArraySize * sizeof(int));
int * B = (int *)malloc((ArraySize) * sizeof(int));
int i=0;
int * c = A;
int * d = B;
for (i = 0;i<ArraySize;i++)
{
*c = i+1;
*d = -1;
c++;
d++;
}
GetPowerSet(0,A,B);
}
/***************************************/
/*The main part of this program*/
/***************************************/
main()
{
char userInput;
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();
}
return 0;
}