|
楼主 |
发表于 2012-9-30 13:46
|
显示全部楼层
递归求和方法改进,提前计算末位值并检查原始数据数组中是否存在有效末位值,
这样大幅减少了递归计算量。
尤其是,计算1-n的连续自然数对象的组合求和时速度最快。- Dim sj, d, jg(), m%, k, h%, cnt
- Sub kagawa_dgH2() '递归组合求和-2
- tms = Timer
- m = [a1].End(4).Row
- h = [b1]
- sj0 = [a1].Resize(m): [a1].Resize(m).Sort [a1], 1, , , 2 '如果原始数据乱序则先升序排序
- sj = [a1].Resize(m)
- [a1].Resize(m) = sj0 '排序处理后原始数据恢复原状
-
- ReDim jg(65536, 0)
- k = 0: cnt = 0
-
- ' Open "D:\Result.txt" For Output As #1
- ' Open "D:\Documents\Result.txt" For Output As #1
- Open "D:\Backup\我的文档\Result.txt" For Output As #1
- '输出结果到记事本文件,地址可以自己修改
- Print #1, m & " / " & h
-
- Call dgH2("", 0, 0, 0)
-
- Print #1, "Result: " & k & "/ Calc " & cnt & "/ Time: " & Format(Timer - tms, "0.000s")
- Close #1
- If k < 65536 Then [d1].CurrentRegion = "": [d1].Resize(k) = jg
- MsgBox "Result: " & k & "/ Calc " & cnt & " Time: " & Format(Timer - tms, "0.000s")
- End Sub
- Sub dgH2(s$, r, i%, t%)
- Dim j%
- cnt = cnt + 1
-
- x = h - r
- If x >= sj(i + 1, 1) Then
- For j = i + 1 To m
- If x = sj(j, 1) Then
- If k < 65536 Then jg(k, 0) = s & "+" & x
- Print #1, s & "+" & x
- k = k + 1
- If k Mod 10000 = 0 Then Application.StatusBar = k & "/" & s
- Exit For
- ElseIf x < sj(j, 1) Then
- Exit For
- End If
- Next
- End If
-
- For j = i + 1 To m - 1
- If x - sj(j, 1) < sj(j + 1, 1) Then
- Exit Sub
- Else
- Call dgH2(s & "+" & sj(j, 1), r + sj(j, 1), j, t + 1)
- End If
- Next j
- End Sub
复制代码 |
|