|
本帖最后由 香川群子 于 2012-10-14 14:37 编辑
主代码中分别调用了两个递归过程
- Dim sj, jg(), ys(), x(), m%, n%, k, h%, cnt
- Sub kagawa_7() '递归组合求和-7 【数组预置结果方法】
- tms = Timer
- m = [a1].End(4).Row: ' sj0 = [a1].Resize(m)
- [a1].Resize(m).Sort [a1], 1, , , 2 '如果原始数据乱序则先升序排序
- sj = [a1].Resize(m, 2): ' [a1].Resize(m) = sj0 '排序处理后原始数据恢复原状
-
- Size = Array(20, 80, 300, 1200, 3800, 12000, 30000, 78000, 190000, 445000) '增加了对x数组大小的自动判断
- ReDim ys(1 To [b1])
- For i = 1 To m
- If i = 1 Then sj(1, 2) = sj(1, 1) Else sj(i, 2) = sj(i - 1, 2) + sj(i, 1)
- h = sj(i, 1)
- If h < [b1] / 2 Then
- ReDim x(Size([b1] / 20)) '根据计算目标和要求定义合适的x数组大小
- k = 1
- Call dgH71(h, "", i + 1)
- x(0) = k - 1
- ReDim Preserve x(k - 1)
- ys(h) = x
- 'Cells(i, 4) = Join(x, ";") '调试时把前期计算好的【数组预置结果】写入工作表确认
- Else
- n = i: Exit For
- End If
- Next
- MsgBox "PreTime: " & Format(Timer - tms, "0.000s")
- ' Exit Sub
-
- ReDim jg(65536, 0)
- k = 0: cnt = 0: tms = Timer
- h = [b1]
-
- Call dgH72(h, "", m + 1)
-
- MsgBox "Result: " & k & "/ Calc " & cnt & " Time: " & Format(Timer - tms, "0.000s")
- If k > 0 And k < 65536 Then [e:e] = "": [e1].Resize(k) = jg
- End Sub
- Sub dgH71(r%, s$, i%) '递归过程-1,仅仅计算返回所有<h/2的组合结果到预置数组中去
- Dim j%
-
- For j = 1 To i - 1
- If IsArray(ys(r)) Then
- For t = ys(r)(0) To 1 Step -1
- If Val(s) > Val(ys(r)(t)) Then
- x(k) = s & ys(r)(t)
- k = k + 1
- End If
- Next
- Exit For
- ElseIf r = sj(j, 1) Then
- x(k) = s & "+" & r
- k = k + 1
- Exit For
- ElseIf r < sj(j, 1) Then
- j = j + 1
- Exit For
- End If
- Next
-
- For j = j - 1 To 2 Step -1
- If r > sj(j, 2) Then
- Exit For
- Else
- Call dgH71(r - sj(j, 1), s & "+" & sj(j, 1), j)
- End If
- Next
- End Sub
- Sub dgH72(r%, s$, i%) '递归过程-2,用来计算本次最终结果。其中余数部分直接调用【数组预置结果】以提高速度。
- Dim j%
- cnt = cnt + 1
-
- For j = 1 To i - 1
- If IsArray(ys(r)) Then
- For t = ys(r)(0) To 1 Step -1
- If sj(i, 1) <= Val(ys(r)(t)) Then Exit For
- ' ss = s & ys(r)(t)
- ' jg(k, 0) = s & ys(r)(t)
- k = k + 1
- Next
- Exit For
- ElseIf r = sj(j, 1) Then
- ' ss = s & "+" & r
- ' jg(k, 0) = s & "+" & r
- k = k + 1
- Exit For
- End If
- Next
-
- For j = j - 1 To 2 Step -1
- Call dgH72(r - sj(j, 1), s & "+" & sj(j, 1), j)
- Next
- End Sub
复制代码
比速度1-160最快(数组预置法).rar
(33.41 KB, 下载次数: 142)
|
|