求幂集的算法

来源:互联网 发布:手机淘宝关闭智能联想 编辑:程序博客网 时间:2024/05/29 02:06

所谓幂集,就是一个集合的子集的集合。

下面是两个不同的实现。

1. 

#include "stack.h"#include <stdio.h>void PowerSet(int i, int *a, int size_of_a, struct stack *s){if( i == size_of_a){int k = 0;int len = size(s);while(k < len){int tmp = 0;peek(s, k, &tmp);printf("%d ", tmp);k++;}printf("\n");}else{push(s, a[i]);PowerSet(i + 1, a, size_of_a,  s);int tmp;pop(s, &tmp);PowerSet(i + 1, a, size_of_a, s);}}int main(int argc, char **argv){int a[] = {100, 89, 3};struct stack s;init(&s);PowerSet(0, a, 3, &s);return 0;}
stack代码如下:

#ifndef _STACK_QUEUE_H_#define _STACK_QUEUE_H_#define MAX_STACK_SIZE 100#ifndef booltypedef unsigned char bool;#endif#ifndef true#define true 1#endif#ifndef false#define false 0#endifstruct stack{int array[MAX_STACK_SIZE];int top;};void init(struct stack *pStack);bool pop(struct stack *pStack, int *pElement);bool push(struct stack *pStack, int element);int size(struct stack *pStack);bool peek(struct stack *pStack, int index, int *element);#endif

#include "stack.h"#include <stdio.h>void init(struct stack *pStack){pStack->top = -1;}bool push(struct stack *pStack, int element){if(pStack->top >= MAX_STACK_SIZE - 1){printf("stack is full\n");return false;} pStack->top++;pStack->array[pStack->top] = element;return true;}bool pop(struct stack *pStack, int *pElement){if(pStack->top < 0){printf("stack is empty\n");return false;}*pElement = pStack->array[pStack->top];pStack->top--;return true;}int size(struct stack *pStack){return pStack->top + 1;}bool peek(struct stack *pStack, int index, int *element){if(index >= size(pStack)){return false;}*element = pStack->array[index];return true;}
实现2:

static int b[3];    void backtrack(int a[], int k, int n)      {          if(k == n - 1)          {              int i;              for(i = 0; i <= k; i++)              {                  if(a[i] == 1)                  {                      printf("%d ", b[i]);                  }              }              printf("\n");          }          else          {              int c[2] = {1, 0};              int i;              k++;              for(i = 0; i < 2; i++)              {                  a[k] = c[i];                  backtrack(a, k, n);              }          }         }                  int main(void)      {          int a[3];  b[0] = 10;b[1] = 98;b[2] = 1;        backtrack(a, -1, 3);          return 0;      }  


0 0