Dim ss() As Integer = Args(0) '原数组
Dim target As Integer = Args(1) '结果和
Dim currentSum As Integer = Args(2) '累加和
Dim idx As Integer = Args(3) '开始索引
Dim n As Integer = Args(4) '遍历层次。或者叫做取数个数,比如任意取2个数字的和为10,表示n是2;任意取3个数字的和为10,表示n是3
Dim lst As List(Of Integer) = Args(5) '参与计算的数组集合
Dim res As List(Of List(Of Integer)) = Args(6) '结果
If n = 1 Then '表示是已经取的最后一个数字
For i As Integer = idx + 1 To ss.Length - 1 '遍历最后一个数字
If currentSum + ss(i) = target Then '如果和之前的数字累加为10
Dim lst3 As New List(Of Integer)
lst3.AddRange(lst)
lst3.Add(ss(i))
res.Add(lst3) '添加到结果中
End If
Next
Else '还不是最后一个数字
For i As Integer = idx + 1 To ss.Length - 1
Dim lst2 As New List(Of Integer) '新增一个集合,避免重复添加
lst2.AddRange(lst) '添加之前的数字
lst2.Add(ss(i)) '添加新的数字
Functions.Execute("child", ss, target, currentSum + ss(i), i, n - 1, lst2, res) ‘继续计算下一层数字
Next
End If
调用
Dim ss As Integer() = {1, 2, 5, 9, 1, 0, 4, 5}
Dim target As Integer = 10
Dim res As New List(Of List(Of Integer))
Dim lst As List(Of Integer)
For n As Integer = 2 To ss.Length - 1
lst = New List(Of Integer)
Functions.Execute("child", ss, target, 0, - 1, n, lst, res)
Next
'显示结果
For Each re As List(Of Integer) In res
Output.Show(String.Join(", ", re))
Next