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

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

我们都知道,一个含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}

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值