获取VB.NET中List(Of List(Of String))的所有排列

我有一个想法,可以使用递归函数解决我的问题,但老实说,我不知道如何开始。

起点是一个List(Of List(Of String)):

Dim Obj As New List(Of List(Of String))

我想检索所有List(Of String)对象之间的所有组合。

作为示例,假设2个包含以下值的字符串列表:

"a", "b", "c"    
"d", "e"    

这应导致:

"a d"
"a e"
"b d"
"b e"
"c d"
"c e"

最终结果也可以以List(Of String)的形式返回。

我猜想实现递归函数可能有效,但是我不知道如何实现:

Function createPermutations(ByVal Obj As List(Of List(Of String))) As List(Of String)

    Dim Result As New List(Of String)

    ...
    Result = createPermutations(...)
    ...

    Return Result

End Function
评论
  • 爷不缺孙子
    爷不缺孙子 回复
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Obj As New List(Of List(Of String))
    
        Dim x As New List(Of String)
        x.Add("a")
        x.Add("b")
        x.Add("c")
    
        Dim y As New List(Of String)
        y.Add("d")
        y.Add("e")
    
        Obj.Add(x)
        Obj.Add(y)
    
        For Each x2 As String In createPermutations(0, Obj)
            System.Console.WriteLine(x2)
        Next
    
    End Sub
    
    Function createPermutations(a As Integer, x As List(Of List(Of String)))
        Dim retval As New List(Of String)
    
        If (a = x.Count) Then
            retval.Add("")
            Return retval
        End If
    
        For Each y As String In x(a)
            For Each x2 As String In createPermutations(a + 1, x)
                retval.Add(y.ToString() + " " + x2.ToString())
            Next
        Next
        Return retval
    End Function
    
  • Linda
    Linda 回复

    像这样在内部和外部使用两个循环怎么样?

    Function createPermutations(ByVal Obj As List(Of List(Of String))) As List(Of String)
    
            Dim Result As New List(Of String)
    
            Dim list_1 As New List(Of String)
            Dim list_2 As New List(Of String)
    
    
            For Each itemL1 In list_1
                For Each itemL2 In list_2
                    Result.Add(itemL1 & " " & itemL2)
    
                Next
    
            Next
        
    
            Return Result
    
        End Function