递归,VBA中的多个基本案例

时间:2014-08-05 21:27:45

标签: algorithm vba excel-vba recursion subset-sum

我正在尝试从此链接获取第一个代码块: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并且sum&lt;&gt; 0时,SubSum被设置为等于False并且该函数继续到下一个if语句。我使用的数据集很小,效率不是问题,我只是想了解VBA的语法。

经过一些研究后我发现了这篇文章:Subset sum algorithm in vba 但它没有递归地实现它。

2 个答案:

答案 0 :(得分:4)

或使用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

答案 1 :(得分: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
'