递归与排列

笔者曾写过一个递归与组合的算法(http://www.csdn.net/Develop/read_article.asp?id=23809),下面给出一个排列的递归算法,请大家指教。

Private Sub Command1_Click() ' 列出数组a 的全排列
Dim a(8) As String, temp As String
For i = 0 To 8
a(i) = i
Next
temp = permutation(a, UBound(a))
Debug.Print temp
Debug.Print "共有 " & UBound(Split(temp, vbCrLf)) + 1 & " 种排法!"
End Sub
Function addxtostr(ByVal x0 As String, ByVal xadd As String) As String ' eg: x0: "1,2,3,4",we will add 5 to x0
Dim temp, temp2, all() As String, i As Long
temp = Split(x0, ",")
ReDim all(UBound(temp) + 1)
all(0) = xadd & "," & x0 ' return "5,1,2,3,4"
For i = 1 To UBound(all)
temp2 = temp
temp2(i - 1) = temp2(i - 1) & "," & xadd '  add 5 between every two contunious number
all(i) = Join(temp2, ",")
Next
addxtostr = Join(all, vbCrLf)
Set temp = Nothing
Set temp2 = Nothing
Erase all
End Function
Function permutation(ByRef a() As String, ByVal n As Long) As String '列出数组a 的前n-1 个元素的全排列
Dim i As Long, temp, all() As String
If n = 0 Then permutation = a(0)
If n = 1 Then permutation = a(0) & "," & a(1) & vbCrLf & a(1) & "," & a(0)
If n > 1 Then
temp = Split(permutation(a, n ), vbCrLf) ' 递归
ReDim all(UBound(temp))
For i = 0 To UBound(temp)
all(i) = addxtostr(temp(i), a(n))
Next
permutation = Join(all, vbCrLf)
End If
Erase all
End Function

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值