回溯求幂集算法

来源:互联网 发布:零售超市收银软件 编辑:程序博客网 时间:2024/04/30 21:54

幂集的每个元素是一个集合或者是一个空集。拿集合{A, B, C}来举例,这个集合的幂集为{ {A, B, C}, {A , B}, {A , C}, {B, C},{A}, {B}, {C}, {}}。可以看出分为3中状态:

  1. 空集
  2. 是集合中的一个元素组成的集合
  3. 是集合中的任意两个元素组成的集合
  4. 是集合中的三个元素组成的集合,就是它本身

下面用回溯递归的思想来实现求幂集的算法:

算法思想,集合中每个元素有两种状态,在幂集元素的集合中,不在集合中。可以用一颗二叉树形象的表示回溯遍历的过程

#include <iostream>using namespace std;char *result;char *element;void OutputPowerSet(int len){ //输出幂集中的元素 cout<<"{ ";int eln = 0;for(int i = 0; i < len; i++){if(result[i] != 0){if(eln > 0)cout<<", "<<result[i];elsecout<<result[i];eln++;}}cout<<" }; ";}void PowerSet(int k,int n){if(k > n){OutputPowerSet(n);}else{result[k-1] = element[k-1]; //元素在幂集元素集合中 PowerSet(k+1,n);result[k-1] = 0;//元素不在幂集元素集合中 PowerSet(k+1,n);}}int main(){int num;cin>>num;//输出要求幂集的初始集合元素个数 element = new char[num];result = new char[num];int index = 0;while(index < num){cin>>element[index];  //输入集合元素,这里用字符代替 index++;}PowerSet(1,num);} 


1 0