首页 > 编程语言 >回溯算法_全排列

回溯算法_全排列

时间:2022-12-09 10:44:19浏览次数:45  
标签:排列 End Sub nums 算法 used 回溯 path Public

'给定一个 没有重复 数字的序列,返回其所有可能的全排列。
'示例:
'输入: [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

 

标签:排列,End,Sub,nums,算法,used,回溯,path,Public
From: https://www.cnblogs.com/eyunkeji/p/16968276.html

相关文章