zoukankan      html  css  js  c++  java
  • 求集合的幂集【转】

    http://www.wutianqi.com/?p=1157

    集合A的幂集是由集合A的所有子集所组成的的集合。

    如:A={1,2,3},则A的幂集P(A)={{1,2,3},{1,2},{1,3},{1},{2,3},{2},{3},{ }}。

    求一个集合的幂集就是求一个集合的所有的子集,方法有穷举法,分治法,回溯等,这里主要介绍一下回溯法

    回溯法是设计递归过程的一种重要的方法,它的求解过实质上是一个先序遍历一棵“状态树”的过程,只是这棵树不是遍历前预先建立的,而是隐含在遍历过程中的。

    幂集中的每个元素是一个集合,它或是空集,或含集合A中一个元素,或含集合A中两个元素…… 或等于集合A。反之,从集合A 的每个元素来看,它只有两种状态:它或属幂集的无素集,或不属幂集的元素集。则求幂集p(A)的元素的过程可看成是依次对集合A中元素进行“取”或“舍”的过程,并且可以用一棵二叉树来表示过程中幂集元素的状态变化过程,树中的根结点表示幂集元素的初始状态(空集);叶子结点表示它的终结状态,而第i层的分支结点,则表示已对集合A中前i-1个元素进行了取舍处理的当前状态(左分支表示取,右分支表示舍 )。因此求幂集元素的过程即为先序遍历这棵状态树的过程。

    具体算法如下:

     1 #include <iostream>
     2 #include <cstring>
     3 #include <ctype.h>
     4 #include <stdlib.h>
     5 #include <string>
     6 using namespace std;
     7  
     8 char a[100];
     9 char b[100];
    10  
    11 void GetPowerSet(int i, char a[])
    12 {
    13     char x;
    14     int k;
    15     int len = strlen(a);
    16     if(i >= len)
    17     {
    18         if(b[0])
    19             cout << b <<  endl;
    20         else
    21             cout << "XX" << endl;  // 表示空集
    22     }
    23     else
    24     {
    25         x = a[i];
    26         k = strlen(b);
    27         b[k] = x;
    28         GetPowerSet(i+1, a);
    29         b[k] = 0;
    30         GetPowerSet(i+1, a);
    31     }
    32 }
    33  
    34  
    35 int main()
    36 {
    37     while(scanf("%s", a) != EOF)
    38     {
    39         printf("%s的幂集是:
    ", a);
    40         printf("------------
    ");
    41         GetPowerSet(0, a);
    42         printf("------------
    ");
    43     }
    44 }
  • 相关阅读:
    hdu 4864(2) 线段树
    hdu 4864
    Codeforces Round #256 (Div. 2)
    BestCoder Round #1 1001 && 1002 hdu 4857 4858
    [Groovy]Parse properties file in Groovy
    [Shell]Shell学习笔记之for
    [转]Groovy Goodness
    SoapUI Properties的使用
    [转]Groovy One Liners to Impress Your Friends
    How can I use wget in Windows
  • 原文地址:https://www.cnblogs.com/huashanqingzhu/p/3523777.html
Copyright © 2011-2022 走看看