递归算法的法则是太极原理,一生二,二生四,四生八,八生十六
Sub xi(a, arr, x As Long, y As Long, z As Long, jj As Long)
Call xi(a & " " & arr(x, 1), arr, x + 1, y + 1, z, jj) '相当于1
Call xi(a, arr, x + 1, y, z, jj) '相当于0
End Sub
1, 0
1 0 1 0
1 0 1 0 1 0 1 0
递归是需要有退出程序的要不然就没完没了了 If x = UBound(arr) + 1 Then Exit Sub
为了提高效率还得剪枝,即减少一些无用功,即前面0太多了,后面未计算的个数加上前面的已组合的个数都不足已最终组成需要的数量 If y + UBound(arr) - x + 1 < z Then Exit Sub
If y = z Then 已满足Z个数的组合后打印结果并结果递归.
jj = jj + 1
Print #1, a
Exit Sub
End If
Sub peng()
aa = Timer
Dim jj As Long, cc As Long
Open "d:\peng.txt" For Output As #1
arr = Range("A1:A" & [A65536].End(xlUp).Row)
Call xi("", arr, 1, 0, Cells(1, 2), jj)
Close #1
MsgBox "找到 " & jj & " 个解! 花费" & Format(Timer - aa, "0.00" & "保存在D:\peng.txt") & "秒"
End Sub
Sub xi(a, arr, x As Long, y As Long, z As Long, jj As Long)
If y = z Then
jj = jj + 1
Print #1, a
Exit Sub
End If
If x = UBound(arr) + 1 Then Exit Sub
If y + UBound(arr) - x + 1 < z Then Exit Sub
Call xi(a & " " & arr(x, 1), arr, x + 1, y + 1, z, jj) '字附串和数字的处理速度是相差很大的
Call xi(a, arr, x + 1, y, z, jj)
End Sub