|
版主,很想弄懂您的算法思路,能不能解释一下,多谢!
pengxiren() '彭版数组法组合求和
Application.ScreenUpdating = False
aa = Timer
Dim arr(1 To 11, 1 To 2) As Integer
Dim a As String
Dim Z As Integer, arr1
Dim i As Integer
Dim c As Long
Dim sum1 As Long
Dim sum2 As Long
Dim x As Long
Dim y As String
Dim bh As Long
Dim G As Long
Dim ren As Byte
Columns("A:A").Select
Selection.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod _
:=xlPinYin
Open "d:\peng.txt" For Output As #1
Z = [A65536].End(xlUp).Row
arr1 = Range("a1", Cells(Z, 1))
x = Cells(1, 2)
For i = 1 To Z
arr(i, 1) = arr1(i, 1)
sum1 = sum1 + arr(i, 1)
If sum1 <= x / 4 Then ren = i
Next i
c = 0
cc = 3
sum1 = 0
Do While arr(Z + 1, 2) < 1
Do While sum1 < x
sum2 = sum1
For i = 1 To 11
If x <= sum2 + arr(i, 1) Then
arr(i, 2) = 1
sum1 = sum1 + arr(i, 1)
If i > bh Then bh = i '找出变化的量,从而知道从那里开始相加
Exit For
End If
If arr(i, 2) = 1 Then
arr(i, 2) = 0
sum1 = sum1 - arr(i, 1)
Else
sum2 = sum2 + arr(i, 1)
End If
Next i
Loop
If bh > G Then G = bh '最大数行号
If bh > ren Then
y = arr(G, 1)
For i = G - 1 To ren + 1 Step -1
If arr(i, 2) = 1 Then
y = y & "+" & arr(i, 1)
End If
Next i
End If
a = y
For i = ren To 1 Step -1
If arr(i, 2) = 1 Then a = a & "+" & arr(i, 1)
Next i
c = c + 1
' Print #1, a
bh = 1
Do While sum1 >= x
For i = 1 To 400
If arr(i, 2) = 1 Then
arr(i, 2) = 0
sum1 = sum1 - arr(i, 1)
Else
If sum1 < x Then
arr(i, 2) = 1
sum1 = sum1 + arr(i, 1)
If i > bh Then bh = i '找出变化的量,从而知道从那里开始相加
If sum1 = x Then Exit Do
Exit For
End If
End If
Next i
Loop
Loop
Close #1
MsgBox "找到 " & c & " 个解! 花费" & Format(Timer - aa, "0.000s") & " 保存在 D:\peng.txt"
End Sub |
|