我有很好的代码来获取Python中的子集总和:
# Python3 program to print sums of
# all possible subsets.
# Prints sums of all subsets of arr[l..r]
def subsetSums(arr, l, r, sum = 0):
# Print current subset
if l > r:
print (sum, end = " ")
return
# Subset including arr[l]
subsetSums(arr, l + 1, r, sum + arr[l])
# Subset excluding arr[l]
subsetSums(arr, l + 1, r, sum)
# Driver code
arr = [5.76, 4.45, 3.2]
n = len(arr)
subsetSums(arr, 0, n - 1)
如何在Excel VBA中执行相同的操作?
答案 0 :(得分:1)
试试这段代码:
Function subsetSums(arr As Variant, l As Long, r As Long, sum As Long)
If l > r Then
Debug.Print (sum)
Exit Function
End If
'Subset including arr[l]
a = subsetSums(arr, l + 1, r, sum + arr(l))
'Subset excluding arr[l]
a = subsetSums(arr, l + 1, r, sum)
End Function
Sub Driver()
Dim arr As Variant
arr = Array(1, 3, 5)
a = subsetSums(arr, LBound(arr), UBound(arr), 0)
End Sub
在代码中,a
变量仅用于满足VBA语法,当您调用函数时,其结果必须分配给变量。