Public path As New Collection
Public cnt As Long
Public res_ar() As Variant
Sub 回溯算法_组合问题()
cnt = 0
Call combine(9, 2)
With Sheet6
.Cells.ClearContents
.Range("a1").Resize(UBound(res_ar)) = Application.Transpose(res_ar)
End With
End Sub
Sub combine(n, k)
Call combineHelper(n, k, 1)
End Sub
Private Sub combineHelper(n, k, startIndex)
If path.count = k Then
Call outRes(path)
Exit Sub
End If
For i = startIndex To n - (k - path.count) + 1
path.Add (i)
Call combineHelper(n, k, i + 1)
path.Remove (path.count)
Next
End Sub
Sub outRes(path)
cnt = cnt + 1
ReDim Preserve res_ar(1 To cnt)
For x = 1 To path.count
tem = tem & path(x)
Next
res_ar(cnt) = tem
End Sub