我正试图从这个链接获取第一段代码: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]);}然后把它转换成一个递归的vba函数,我打算从sub调用它。到目前为止我有: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但它不是递归实现的。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 或者使用ELSIF来避免退出功能Sub test()Dim arr() As VariantDim sum As LongDim n As LongDim result As Boolean arr = Array(3, 34, 4, 12, 5, 2) n = 9 result = SubSum(arr, UBound(arr), n)End SubFunction 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 IfEnd Function (adsbygoogle = window.adsbygoogle || []).push({});
10-08 08:19