# 如何得到某集合的所有子集合?

{}           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}
{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}

• 本文已收录于以下专栏：

举报原因： 您举报文章：如何得到某集合的所有子集合? 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)