回溯算法_全排列

'给定一个 没有重复 数字的序列,返回其所有可能的全排列。
'示例:
'输入: [1,2,3]
'输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

Public path As New Collection
Public used(2) As Boolean
Public k As Long

Sub 回溯算法_全排列()
    k = 0
    Sheet7.Cells.ClearContents
    nums = Array(1, 2, 3)
    Call permuteHelper(nums)
End Sub

Public Sub permuteHelper(nums)
    If path.count = UBound(nums) + 1 Then
        k = k + 1
        s = path(1) & path(2) & path(3)
        Sheet7.Cells(k, 1) = s
    End If
    For i = 0 To UBound(nums)
        If used(i) = False Then
            used(i) = True
            path.Add (nums(i))
            permuteHelper (nums)
            path.Remove (path.count)
            used(i) = False
        End If
    Next
End Sub

 

posted @ 2022-12-09 10:39  依云科技  阅读(31)  评论(0)    收藏  举报