'递归函数,用于数组中寻找N项之和等于目标值的组合
Dim str As String = args(0) '原始数组
Dim nums() As String = str.Split(",") '将str内容拆分成数组
Array.Sort(nums)
Dim target As Decimal=args(1) '目标值
Dim n As Integer= args(2) 'N项,N张fa piao号码
Dim StartIndex As Integer = args(3) '一般为0
Dim sum As Decimal
Dim result() As Decimal
'当n=2时,转为寻找两项之和等于目标值的问题
If n = 2 Then
Dim left As Integer = StartIndex '左指针从STRARTINDEX开始
Dim right As Integer = nums.length - 1
'使用双指针法搜索满足条件的组合
Do While left < right
sum = val(nums(left)) + val(nums(right))
'MessageBox.Show(nums(left))
'MessageBox.Show(nums(right))
' MessageBox.Show("sum:="&sum)
' MessageBox.Show("target:="&target)
If sum = target Then
result = New Decimal() {nums(left),nums(right)}'找到一组解,加入结果数组
messagebox.Show(result(0))
messagebox.Show(result(1))
left = left +1
right = right - 1
'跳过重复的元数
Do While left < right And nums(left) = nums(left - 1)
left = left +1
Loop
Do While left < right And nums(right) = nums(right + 1)
right = right - 1
Loop
'跳过重复的元数 end
ElseIf sum < target Then
left = left +1
Else
right = right -1
End If
Loop
Else
'当N不等于2时,使用递归寻找N-1项之和等于targe 减去当前项的组合
Dim i As Integer
For i = startindex To nums.length - n + 1
If i = startindex Or nums(i) <> nums(i-1) Then
Functions.Execute("N个数和等于M",nums,target - nums(i),n-1,i+1)
End If
Next
End If