【发布时间】: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 ThenSubSum = 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