【问题标题】:Recursion, multiple base cases in VBA递归,VBA中的多个基本案例
【发布时间】:2014-08-05 21:27:45
【问题描述】:

我正在尝试从此链接获取第一块代码:http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/ 复制粘贴如下:

bool isSubsetSum(int set[], int n, int sum)
{
   // Base Cases
   if (sum == 0)
     return true;
   if (n == 0 && sum != 0)
     return false;

   // If last element is greater than sum, then ignore it
   if (set[n-1] > sum)
     return isSubsetSum(set, n-1, sum);

   /* else, check if sum can be obtained by any of the following
      (a) including the last element
      (b) excluding the last element   */
   return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]);
}

并将其转换为我计划从 Sub 调用的递归 VBA 函数。

到目前为止我有:

Function SubSum(source(), n As Integer, sum)

    If sum = 0 Then
        SubSum = True
    End If
    If (n = 0 And sum <> 0) Then
        SubSum = False
    End If

    If source(n - 1) > sum Then
        SubSum = SubSum(source, n - 1, sum)
    End If

    SubSum = (SubSum(source, n - 1, sum) Or SubSum(source, n - 1, sum - source(n - 1)))

End Function

我的问题是在每个基本情况下返回一个值不会退出该函数的实例。因此,当 n=0 且 sum0 时,SubSum 设置为 False,函数继续执行下一个 if 语句。我使用的数据集很小,效率不是问题,我只是想了解VBA的语法。

在做了一些研究后,我发现了这个帖子:Subset sum algorithm in vba 但它并没有递归地实现它。

【问题讨论】:

  • Function SubSum(source(), n As Integer, sum) If sum = 0 Then SubSum = True GoTo RecurJump End If (n = 0 And sum 0) Then SubSum = False GoTo RecurJump End If If if source(n - 1) > sum Then SubSum = SubSum(source, n - 1, sum) GoTo RecurJump End If SubSum = (SubSum(source, n - 1, sum) 或 SubSum(source, n - 1, sum - source(n - 1))) RecurJump:结束函数`
  • 我无法弄清楚如何将代码放入 cmets,但我发现这是一个功能性的解决方法,但样式仍然非常错误。 pastebin.com/0tMqyLnY如果有人发现更好的东西,请告诉我。如果链接到 pastebin 违反规则,我深表歉意。

标签: algorithm vba excel recursion subset-sum


【解决方案1】:

或者使用 elseif 来避免退出函数

Sub test()

Dim arr() As Variant
Dim sum As Long
Dim n As Long
Dim result As Boolean

    arr = Array(3, 34, 4, 12, 5, 2)
    n = 9
    result = SubSum(arr, UBound(arr), n)

End Sub


Function SubSum(source As Variant, n As Long, sum As Long) As Boolean

    If sum = 0 Then
        SubSum = True

    ElseIf (n = 0 And sum <> 0) Then
        SubSum = False

    ElseIf source(n - 1) > sum Then
        SubSum = SubSum(source, n - 1, sum)
    Else
        SubSum = (SubSum(source, n - 1, sum) Or SubSum(source, n - 1, sum - source(n - 1)))

    End If
End Function

【讨论】:

  • 不应该避免退出功能,用词错误:)
  • 我已经编辑了我的代码,但是因为你已经发布了它而丢弃了它:)
【解决方案2】:

我的问题是.....并且函数继续到下一个 if 语句。

要解决这个问题,您必须使用Exit Function

例如

'
'~~> Rest of the code
'
If sum = 0 Then
    SubSum = True
    Exit Function   
ElseIf (n = 0 And sum <> 0) Then
    SubSum = False
    Exit Function
End If
'
'~~> Rest of the code
'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2022-01-19
    • 2017-07-11
    • 2020-01-25
    • 2017-03-04
    相关资源
    最近更新 更多