给你一段VBA代码吧,放入EXCEL的代码页中(ALT+F11),运行主程序MYCMB()就会把结果输出到表格中。
Sub MYCMB()
Const t = 5, Z = 8 '从8个数字中取5个进行组合
Dim CNO, q(), CM(), CM2()
st = Timer
'为保证速度,用数组存储结果
ReDim q(1 To t)
ReDim CM(1 To WorksheetFunction.combin(Z, t))
nq 1, 1, t, Z, CNO, q(), CM()
'转二维数组,以便EXCEL存放
ReDim CM2(1 To CNO, 1 To t)
For i = 1 To CNO
For j = 1 To t
CM2(i, j) = CM(i)(j)
Next j
Next i
'输出结果到表格
Cells(1, t + 2) = "组合数"
Cells(1, t + 3) = CNO
If CNO > 65536 Then CNO = 65536
Range(Cells(1, 1), Cells(CNO, t)) = CM2
Cells(2, t + 2) = "运行时间(秒)"
Cells(2, t + 3) = Timer - st
End Sub
'递归函数
Sub nq(n, s, x, E, CNO, q(), CM())
For i = s To E - x + n
q(n) = i
If n = x Then '当前组合的数字已经选完
CNO = CNO + 1
CM(CNO) = q
Else
nq n + 1, i + 1, x, E, CNO, q(), CM()
End If
Next i
End Sub