递归与排列

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 northwolves 的 blog

笔者曾写过一个递归与组合的算法(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

本文关键:递归 排列
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top