问题描述
我正在尝试使用VBA运行一个动态编程示例,该示例应通过将值存储在字典中来限制递归调用该函数的次数。
我遇到的问题是在可以使用生成的键将值存储在字典中之前递归调用该函数。通常,我会在字典键存储关联值之后使用'return'关键字,但这在VBA中似乎不起作用。
Public Function count_sets_dp(arr,total)
Dim mem As Dictionary
Set mem = New Dictionary
count_sets_dp = dp(arr,total,GetArrLength(arr),mem)
最后的“ else”子句将启动递归调用,而不会将结果存储在mem(key)中。
Public Function dp(arr,i,mem)
'dynamic programming or memoized solution
Dim Key As String
Dim to_return As Integer
Key = CStr(total) & ":" & CStr(i)
If mem.Exists(Key) Then
dp = mem(Key)
End If
If total = 0 Then
dp = 1
ElseIf total < 0 Then
dp = 0
ElseIf i < 1 Then
dp = 0
ElseIf total < arr(i) Then
to_return = dp(arr,i - 1,mem)
Else: to_return = (dp(arr,total - arr(i),mem) + dp(arr,mem))
mem(Key) = to_return
dp = to_return
End If
End Function
似乎我没有从这里的动态编程解决方案中受益,我试图了解我是否有语法问题...
Sub mysub()
Dim tiMetaken As Double
Dim myArray() As Variant
Dim result As Integer
myArray = [{2,4,6,10,4}]
result = count_sets_dp(myArray,16)
MsgBox (result)
End Sub```
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)