zoukankan      html  css  js  c++  java
  • 如何得到某集合的所有子集合?

    我们都知道,一个含n个元素的集合拥有2^n个子集合,并且不难发现,其中每个子集合都是从0到2^n-1 每个数的二进制格式中0 放弃,1选择的结果,如下所示:

    {}           000

    {1}         100

    {2}         010

    {1,2}      110

    {3}         001

    {1,3}      101

    {2,3}      011

    {1,2,3}   111

    所以根据数字的二进制转换,可以轻松获得一个集合的所有子集合,代码如下:

    Sub GETALL(ByVal mycollection As String, ByRef RESULT() As String)
    Dim x() As String
    x = Split(Mid(mycollection, 2, Len(mycollection) - 2), ",")

    Dim A() As String, b() As Integer '临时数组
    Dim n As Integer ' 集合元素个数
    Dim i As Long '循环变量
    Dim num As Integer '子集合元素个数
    Dim TEMP As Integer '二进制转换中间变量
    n = UBound(x) + 1
    ReDim b(0 To n - 1)
    ReDim RESULT(2 ^ n - 1)
    Debug.Print "集合 " & mycollection & " 共有子集合 " & 2 ^ n & " 个!"

    For i = 0 To 2 ^ n - 1
    TEMP = i
    num = 0
    For j = 0 To n - 1 '转换为二进制
    b(j) = TEMP And 1 '0 or 1
    TEMP = TEMP / 2
    If b(j) = 1 Then
    num = num + 1
    ReDim Preserve A(1 To num)
    A(num) = x(j)
    End If
    Next

    RESULT(i) = "{" & Join(A, ",") & "}" '结果保存
    Debug.Print RESULT(i) '输出

    Next
    MsgBox "OK"
    End Sub

    Private Sub Command1_Click()
    Dim S() As String
    GETALL "{1,2,3,4,5,6}", S
    End Sub

    输出:

    集合 {1,2,3,4,5,6} 共有子集合 64 个!
    {}
    {1}
    {2}
    {1,2}
    {3}
    {1,3}
    {2,3}
    {1,2,3}
    {4}
    {1,4}
    {2,4}
    {1,2,4}
    {3,4}
    {1,3,4}
    {2,3,4}
    {1,2,3,4}
    {5}
    {1,5}
    {2,5}
    {1,2,5}
    {3,5}
    {1,3,5}
    {2,3,5}
    {1,2,3,5}
    {4,5}
    {1,4,5}
    {2,4,5}
    {1,2,4,5}
    {3,4,5}
    {1,3,4,5}
    {2,3,4,5}
    {1,2,3,4,5}
    {6}
    {1,6}
    {2,6}
    {1,2,6}
    {3,6}
    {1,3,6}
    {2,3,6}
    {1,2,3,6}
    {4,6}
    {1,4,6}
    {2,4,6}
    {1,2,4,6}
    {3,4,6}
    {1,3,4,6}
    {2,3,4,6}
    {1,2,3,4,6}
    {5,6}
    {1,5,6}
    {2,5,6}
    {1,2,5,6}
    {3,5,6}
    {1,3,5,6}
    {2,3,5,6}
    {1,2,3,5,6}
    {4,5,6}
    {1,4,5,6}
    {2,4,5,6}
    {1,2,4,5,6}
    {3,4,5,6}
    {1,3,4,5,6}
    {2,3,4,5,6}
    {1,2,3,4,5,6}

  • 相关阅读:
    2019New XTOOL X100 PAD钥匙编程器:有啥好用的吗?
    AUTEL MaxiSys MS906BT常见问题解答:修改速度限制器,输入VIN号码
    Autel MaxiAP AP200:功能,特性,评论
    OBDSTAR X300 PRO3详细评论
    Autel MaxiIM IM608:关于如何更新和一些评论
    Autel MaxiAP AP200:功能,特性,评论,
    OBDSTAR X300 PRO3详细评论
    k8s 基础总结
    k8s yaml 编写
    k8s 生命周期概况
  • 原文地址:https://www.cnblogs.com/fengju/p/6336388.html
Copyright © 2011-2022 走看看