zoukankan      html  css  js  c++  java
  • 数据结构与算法-第12章二叉树和其他树-001遍历集合的所有子集

    We may represent a subset of n elements by the one-dimensional array x[1:n], where x[j] is one if element j is included in the subset and x[j] is zero if element j is not included in the subset. 

    To output the subsets recursively, we define a method subsets(int i) which outputs all x[1:n] with preset values for x[1:i-1] and x[i:n] taking on all possible 0 and 1 values. The invocation subsets(1) will output all subsets. 

     1 /** generate all subsets of n elements */
     2 
     3 package applications;
     4 
     5 public class AllSubsets
     6 {
     7    // class data member
     8    static int [] x;  // subset vector
     9    
    10    /** define array x and invoke private method subsets */
    11    public static void allSubsets(int n)
    12    {
    13       x = new int [n + 1];
    14       // output all subsets of x[1:n]
    15       subsets(1);
    16    }
    17 
    18    /** output x[1:i-1] followed by all subsets of x[i:x.length-1] */
    19    private static void subsets(int i)
    20    {
    21       if (i == x.length - 1)
    22       {// x[x.length - 1] can be 0 or 1
    23          // output subset without last element
    24          x[x.length - 1] = 0;
    25          for (int j = 1; j <= x.length - 1; j++)
    26             System.out.print(x[j] + " ");
    27          System.out.println();
    28          
    29          // output subset with last element
    30          x[x.length - 1] = 1;
    31          for (int j = 1; j <= x.length - 1; j++)
    32             System.out.print(x[j] + " ");
    33          System.out.println();
    34          return;
    35       }
    36                    
    37       // leave element i out
    38       x[i] = 0;
    39       // generate all subsets with i excluded
    40       subsets(i + 1);
    41                    
    42        // put element i into subset
    43        x[i] = 1;
    44        // generate all subsets with i included
    45        subsets(i + 1);
    46    }
    47     
    48    /** test program */
    49    public static void main(String [] args)
    50    {
    51       allSubsets(4);
    52    }
    53 }

  • 相关阅读:
    linux centos下载地址
    什么是镜像文件?
    Linux下处理JSON的命令行工具:jq---安装
    CentOS7安装第三方yum源EPEL
    CentOS 6.5 下编译安装 Nginx 1.8.0
    CentOS 6.7 如何启用中文输入法
    Linux Yum 命令使用举例
    YUM 安装及清理
    Linux常用命令之rpm安装命令
    使用git代替FTP部署代码到服务器的例子
  • 原文地址:https://www.cnblogs.com/shamgod/p/5387713.html
Copyright © 2011-2022 走看看