注册 登录
编程论坛 VB.NET论坛

请高手出手,全排列

mp654k 发布于 2011-12-30 21:48, 754 次点击
给定一个字符串s,如何将它各个字符的各种排序情况列出来放到一个字符串数组ss?
比如给定s="123",则函数返回值ss={"123","132","213","231","312","321"}
程序,写一个函数,要求是能直接拿来用,效率尽量高点,拒绝穷举法.

[ 本帖最后由 mp654k 于 2011-12-30 21:51 编辑 ]
1 回复
#2
wwf30452012-01-10 22:27
可以使用递归


Public Class Form1


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim result() As String
        TextBox1.Text = ""
        Dim str As String
        str = InputBox("字符串")
        If str.Length = 0 Then
            MsgBox("无字符串", vbCritical + vbOKOnly)
            Exit Sub
        End If

        result = pailie(str)
        '显示结果
        For Each i As String In result
            TextBox1.Text = TextBox1.Text & i & vbCrLf
        Next
    End Sub

    Private Function pailie(ByVal str As String) As String()
        Dim result() As String
        ReDim result(0)
        Dim str2() As String
        If str.Length <= 2 Then
            Dim reverse(1) As String
            reverse(0) = str
            reverse(1) = Strings.StrReverse(str)
            Return reverse
        Else
            For i As Integer = 1 To str.Length
                Dim str1 As String
                Dim t As String
                str1 = Strings.Left(str, i - 1) & Strings.Right(str, str.Length - i)    '排除一个字符
                t = Strings.Mid(str, i, 1)  '记录排除的字符
                str2 = pailie(str1)
                For j As Integer = LBound(str2) To UBound(str2)
                    str2(j) = t & str2(j)   '加上排除的字符
                Next

                '存储临时结果
                ReDim Preserve result(UBound(result) + UBound(str2) + 1)
                For j As Integer = UBound(result) - UBound(str2) To UBound(result)
                    result(j - 1) = str2(UBound(result) - j)
                Next

            Next
            ReDim Preserve result(UBound(result) - 1)
            Return result
        End If
    End Function
End Class
1