• 列出所有子集2013年1月3日


           问题描述:列出一个集合的所有子集,包括空子集合。

           我的思路:回溯法的一种思路就是生成一颗子集树,而一个集合中的元素,要么存在于子集中,要么不存在,所以这又特殊化成一颗二叉树了。每当到达二叉树的底端时,就打印一次。很容易写出如下的代码:

     1 #include <stdio.h>
     2 #define MAX 1000
     3 
     4 int n=3;  //the number of the set elements
     5 int set[MAX]={1,2,3};
     6 int count=0;//the number of the subset.
     7 
     8 void DFS(int level);
     9 void print_set();
    10 
    11 int main()
    12 {
    13     DFS(0);
    14     return 0;
    15 }
    16 
    17 void DFS(int level)
    18 {
    19     if(level==n)
    20     {
    21         print_set();
    22         return ;
    23     }
    24     int save=set[level];
    25     set[level]=0;
    26     int index=0;
    27     for(index=0;index<2;index++)
    28     {
    29         DFS(level+1);
    30         set[level]=save;
    31     }
    32 
    33 }
    34 
    35 void print_set()
    36 {
    37     int index;
    38     count++;
    39     printf("%d: {",count);
    40     for(index=0;index<n;index++)
    41     {
    42         if(set[index]!=0) 
    43             printf("%d ",set[index]);
    44     }
    45     printf("}\n");
    46 }

           如果你觉得我的文章对你有帮助,请推荐一下,非常感谢!

  • 相关阅读:
    CNN做序列标注问题(tensorflow)
    对于梯度消失和梯度爆炸的理解
    LSTM(长短期记忆网络)及其tensorflow代码应用
    Python之禅
    Python namedtuple
    Linux里的2>&1
    PySpark笔记
    平衡二叉树,B树,B+树
    lzo文件操作
    Hadoop的Shell命令
  • 原文地址:https://www.cnblogs.com/NeilHappy/p/2843295.html
Copyright © 2020-2023  润新知