|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 kangren6772 于 2018-12-24 11:06 编辑
给定的固定的金额,比如200元,用100、50、20、10、5、2、1元等金额(可以更多)凑成200的方法的解决办法,本人想了4种,有更好的本人水平有限
,希望高手能给出更好的解答,下面给出我的解法,2种递归,两种循环:
Option Base 1
Dim jg(10000, 1), k&
Sub perpare()
Erase jg: k = 0
Dim arr%(6)
arr(1) = 100: arr(2) = 50
arr(3) = 20: arr(4) = 10
arr(5) = 5: arr(6) = 1
Call rec1(arr(), 1, 0, "")
[a1].Resize(10000) = jg
End Sub
Sub recursion(ByRef arr%(), a%, b%, str$)
If b = 200 Then k = k + 1: jg(k, 1) = Right(str, Len(str) - 1)
If b < 200 And a < UBound(arr) + 1 Then
Call recursion(arr(), a, b + arr(a), str & "+" & arr(a))
Call recursion(arr(), a + 1, b, str)
End If
End Sub
Sub recursion1(ByRef arr%(), a%, b%, str$)
Dim i%
For i = a To UBound(arr)
If b > 200 Then Exit Sub
If b = 200 Then k = k + 1: jg(k, 1) = Right(str, Len(str) - 1): Exit Sub
Call recursion1(arr, i, b + arr(i), str & "+" & arr(i))
Next
End Sub
Sub test()
Dim arr(6), k&
arr(1) = 100: arr(2) = 50
arr(3) = 20: arr(4) = 10
arr(5) = 5: arr(6) = 1
Dim a%, b%, c%, d%, e%, f%
Dim sum1&, sum2&, sum3&, sum4&, sum5&, sum6&
For a = 0 To Int(200 / arr(1))
If sum1 > 200 Then Exit For
If sum1 = 200 Then k = k + 1: Exit For
sum1 = sum1 * a
For b = 0 To Int(200 / arr(2))
sum2 = sum1
If sum2 > 200 Then Exit For
If sum2 = 200 Then k = k + 1: Exit For
sum2 = sum2 + b * arr(2)
For c = 0 To Int(200 / arr(3))
sum3 = sum2
If sum3 > 200 Then Exit For
If sum3 = 200 Then k = k + 1: Exit For
sum3 = sum3 + c * arr(3)
For d = 0 To Int(200 / arr(4))
sum4 = sum3
If sum4 > 200 Then Exit For
If sum4 = 200 Then k = k + 1: Exit For
sum4 = sum4 + d * arr(4)
For e = 0 To Int(200 / arr(5))
sum5 = sum4
If sum5 > 200 Then Exit For
If sum5 = 200 Then k = k + 1: Exit For
sum5 = sum5 + e * arr(5)
For f = 0 To Int(200 / arr(6))
sum6 = sum5
If sum6 > 200 Then Exit For
If sum6 = 200 Then k = k + 1: Exit For
sum6 = sum6 + f * arr(6)
Next f, e, d, c, b, a
'Debug.Print k
End Sub
Sub test()
k = 0
arr(1) = 100: arr(2) = 50: arr(3) = 20: arr(4) = 10
arr(5) = 5: arr(6) = 1: Const rel = 200
Dim a%, b%, i%, j%, zz%(6), zt%(6), sum&
For a = 1 To UBound(arr): zz(a) = rel \ arr(a): Next
i = UBound(arr)
Do
sum = 0: j = 0
For a = i To 1 Step -1
If zt(a) < zz(a) Then Exit For
Next
If a = 0 Then Exit Do
zt(a) = zt(a) + 1
For b = a + 1 To 6: zt(b) = 0: Next
i = UBound(arr): For b = 1 To a: sum = sum + zt(b) * arr(b): Next
Do
If sum = rel Then k = k + 1: i = i - 1: Exit Do
If sum > rel Then: i = i - 1: Exit Do
sum = sum + arr(i)
Loop
Loop
'Debug.Print k
End Sub
|
|