回溯实现数组元素的排列组合
参考http://blog.csdn.net/northwolves/archive/2007/08/29/1764177.aspx中的代码,将字符串数组x取n个元素进行排列组合:
Sub getall(ByRef x() As String, ByVal n As Byte, Optional types As Byte = 0)
Dim m As Long, num As Long, i As Integer, j As Integer, min As Integer, k As Integer, a(), b() As String, s() As String
ReDim a(1 To n)
ReDim b(1 To n)
m = UBound(x) - LBound(x) + 1
min = LBound(x) - 1
k = 1
If m < n Then Exit Sub
Do
a(k) = a(k) + 1
If a(k) > m Then
k = k - 1
Else
For i = 1 To k - 1
If a(k) = a(i) Then Exit For
Next
If i = k Then
If k = n Then
For j = 1 To n
b(j) = x(min + a(j))
Next
num = num + 1
ReDim Preserve s(1 To num)
s(num) = Join(b, ",")
End If
If k < n Then k = k + 1: a(k) = a(k - 1) * types
End If
End If
Loop Until k = 0
Debug.Print Join(s, vbTab)
End Sub
Sub getit()
Dim x() As String
x = Split("a b c d e f g")
getall x, 4, 1 '组合
Debug.Print
getall x, 3 '排列
End Sub
返回:
a,b,c,d a,b,c,e a,b,c,f a,b,c,g a,b,d,e a,b,d,f a,b,d,g a,b,e,f a,b,e,g a,b,f,g a,c,d,e a,c,d,f a,c,d,g a,c,e,f a,c,e,g a,c,f,g a,d,e,f a,d,e,g a,d,f,g a,e,f,g b,c,d,e b,c,d,f b,c,d,g b,c,e,f b,c,e,g b,c,f,g b,d,e,f b,d,e,g b,d,f,g b,e,f,g c,d,e,f c,d,e,g c,d,f,g c,e,f,g d,e,f,g
a,b,c a,b,d a,b,e a,b,f a,b,g a,c,b a,c,d a,c,e a,c,f a,c,g a,d,b a,d,c a,d,e a,d,f a,d,g a,e,b a,e,c a,e,d a,e,f a,e,g a,f,b a,f,c a,f,d a,f,e a,f,g a,g,b a,g,c a,g,d a,g,e a,g,f b,a,c b,a,d b,a,e b,a,f b,a,g b,c,a b,c,d b,c,e b,c,f b,c,g b,d,a b,d,c b,d,e b,d,f b,d,g b,e,a b,e,c b,e,d b,e,f b,e,g b,f,a b,f,c b,f,d b,f,e b,f,g b,g,a b,g,c b,g,d b,g,e b,g,f c,a,b c,a,d c,a,e c,a,f c,a,g c,b,a c,b,d c,b,e c,b,f c,b,g c,d,a c,d,b c,d,e c,d,f c,d,g c,e,a c,e,b c,e,d c,e,f c,e,g c,f,a c,f,b c,f,d c,f,e c,f,g c,g,a c,g,b c,g,d c,g,e c,g,f d,a,b d,a,c d,a,e d,a,f d,a,g d,b,a d,b,c d,b,e d,b,f d,b,g d,c,a d,c,b d,c,e d,c,f d,c,g d,e,a d,e,b d,e,c d,e,f d,e,g d,f,a d,f,b d,f,c d,f,e d,f,g d,g,a d,g,b d,g,c d,g,e d,g,f e,a,b e,a,c e,a,d e,a,f e,a,g e,b,a e,b,c e,b,d
e,b,f e,b,g e,c,a e,c,b e,c,d e,c,f e,c,g e,d,a e,d,b e,d,c e,d,f e,d,g e,f,a e,f,b e,f,c e,f,d e,f,g e,g,a e,g,b e,g,c e,g,d e,g,f f,a,b f,a,c f,a,d f,a,e f,a,g f,b,a f,b,c f,b,d f,b,e f,b,g f,c,a f,c,b f,c,d f,c,e f,c,g f,d,a f,d,b f,d,c f,d,e f,d,g f,e,a f,e,b f,e,c f,e,d f,e,g f,g,a f,g,b f,g,c f,g,d f,g,e g,a,b g,a,c g,a,d g,a,e g,a,f g,b,a g,b,c g,b,d g,b,e g,b,f g,c,a g,c,b g,c,d g,c,e g,c,f g,d,a g,d,b g,d,c g,d,e g,d,f g,e,a g,e,b g,e,c g,e,d g,e,f g,f,a g,f,b g,f,c g,f,d g,f,e