如何得到某集合的所有子集合?
我们都知道,一个含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}