当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

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


我们都知道,一个含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 Stringx = 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) + 1ReDim b(0 To n - 1)ReDim RESULT(2 ^ n - 1)Debug.Print "集合 " & mycollection & " 共有子集合 " & 2 ^ n & " 个!"
For i = 0 To 2 ^ n - 1TEMP = inum = 0For j = 0 To n - 1 '转换为二进制b(j) = TEMP And 1 '0 or 1TEMP = TEMP \ 2If b(j) = 1 Thennum = num + 1ReDim Preserve A(1 To num)A(num) = x(j)End IfNext
RESULT(i) = "{" & Join(A, ",") & "}" '结果保存Debug.Print RESULT(i) '输出
NextMsgBox "OK"End Sub
Private Sub Command1_Click()Dim S() As StringGETALL "{1,2,3,4,5,6}", SEnd 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}
相关内容
赞助商链接