前边我的帖子结果计算错误。但结果c(m-n+1,n)应该没错,干么不用递归?
Private Sub Command1_Click()
MsgBox getcount(8, 3)
End Sub
Function comb(ByVal m As Integer, ByVal n As Integer) As Long
If n > m Then Exit Function
If m = 1 And n = 0 Then comb = 1
If m = 1 And n = 1 Then comb = 1
If m > 1 Then comb = comb(m - 1, n - 1) + comb(m - 1, n)
End Function
Function getcount(ByVal m As Integer, ByVal n As Integer) As Long
If n > m / 2 Then Exit Function
getcount = comb(m - n + 1, n)
End Function
如果要列出所有取法我觉得还是递归好些。
Public Function GetCount(M As Long, n As Long) As Long
Dim lM1 As Long, lM2 As Long
Dim i1 As Long, i2 As Long, i3 As Long
Dim Count As Long, Count1 As Long, Count2 As Long, Count3 As Long
On Error GoTo ErrHandle
If (M <= 0) Or (n <= 0) Or (n * 2) > M Then
MsgBox "错误的参数"
GoTo ErrHandle
End If
lM1 = M \ 2
lM2 = M - lM1
Count = fact(lM2) / (fact(lM2 - n) * fact(n))
For i1 = 1 To n
Count1 = fact(lM1) / (fact(lM1 - i1) * fact(i1))
Count3 = 0
For i2 = i1 + 1 To (2 * i1) Mod (lM2 + 1)
Count2 = fact(lM2 - i2) / (fact((lM2 - i2) - (n - i1)) * fact(n - i1))
Count3 = Count3 + Count2
Next i2
Count = Count + Count1 * Count3
Next i1
GetCount = Count
Exit Function
ErrHandle:
GetCount = 0
End Function
Function fact(ByVal x As Long) As Long '求阶乘
fact = 1
Dim i As Long
For i = 1 To x
fact = fact * i
Next
End Function
Private Sub Command1_Click()
MsgBox GetCount(15, 7)
End Sub
Function fact(ByVal x As Long) As Long '求阶乘
fact = 1
Dim i As Long
For i = 1 To x
fact = fact * i
Next
End Function
Function comb(ByVal m As Integer, ByVal n As Integer) As Long '求组合
comb = fact(m - n + 1) * fact(m + 2 - 2 * n) / fact(n)
End Function
Private Sub Command1_Click() '计算15个数中选7个的方法
Const m = 15
Const n = 7
MsgBox comb(m, n)
End Sub