【算法】反求 一个值是已知数组中某几个元素值的和
如题:
int a = 11;
int[] x = new int[]{2,7,5,3,4};
求 11 = 2 + 5 + 4;或者 11 = 7 + 4;
好久没来了,顺便向坚守vb的人们致敬......
[解决办法]
VB.net啊
[解决办法]
递归吧
[解决办法]
循环穷举而已。你可以设置一些判断来减少计算量,例如,预先升序排序,当计算到结果已经大于目标值时,就跳出当前循环。
[解决办法]
贪婪法咯
排序
选合适而又最大那个,一直选下去咯
[解决办法]
Private Sub Command1_Click()
Dim num(1 To 10) As Long
Dim i As Long
For i = 1 To 10
num(i) = i
Next
For i = 1 To 10
SumX CStr(num(i)), num(i), 11, i + 1, num
Next
End Sub
Private Sub SumX(strPre As String, nOp1 As Long, nSum As Long, nStart As Long, aArr() As Long)
Dim i As Long
For i = nStart To UBound(aArr)
If nOp1 + aArr(i) = nSum Then
Debug.Print strPre & "+ " & CStr(aArr(i)) & "= " & CStr(nSum)
End If
SumX strPre & "+ " & CStr(aArr(i)), nOp1 + aArr(i), nSum, i + 1, aArr()
Next
End Sub