# 如何用递归实现n个数的全排列?

• ### 问题

• 如题,求vb.net的代码,谢谢!

Work8862

2014年8月4日 14:21

### 答案

• 如题,求vb.net的代码,谢谢!

Work8862

Hi,

有关全排列的算法问题， 推荐你看一下这个博客

http://www.cnblogs.com/bakari/archive/2012/08/02/2620826.html

了解了算法后，具体实现就比较容易了。

参考例子：

```Module Module1

Sub Main()
Dim str As String = "123"
Dim lst() As Char = str.ToCharArray()

Dim st As String = New String(lst)
Perm(lst, 0, lst.Length - 1)
End Sub

Dim lstResult As New List(Of String)
Dim indexRS As Integer = 1
Sub Perm(lstCh() As Char, k As Integer, m As Integer)
If k = m Then
Console.WriteLine("第{0}个排列：{1}", indexRS.ToString(), New String(lstCh))
indexRS += 1
Else
For index = k To m
If NeedSwap(lstCh, k, index) Then
Swap(lstCh, k, index)
Perm(lstCh, k + 1, m)
Swap(lstCh, k, index)
End If
Next

End If
End Sub
Function NeedSwap(lstCh() As Char, nBegin As Integer, nEnd As Integer) As Boolean
For index = nBegin To nEnd - 1
If lstCh(index) = lstCh(nEnd) Then
Return False
End If
Next
Return True
End Function

Sub Swap(lstCh() As Char, a As Integer, b As Integer)
Dim temp As Char = lstCh(a)
lstCh(a) = lstCh(b)
lstCh(b) = temp
End Sub
End Module```

Regards.

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.