回溯演算法_全排列_元素重複_字典去重法
阿新 • • 發佈:2022-12-09
'示例 1: '輸入: nums = [1,1,2] '輸出: [[1,1,2], [1,2,1], [2,1,1]] '示例 2: '輸入: nums = [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 dic As New Dictionary Public used(2) As Boolean Public k As Long Public res_str Sub 回溯演算法_全排列_元素重複_字典去重() k = 0 Sheet7.Cells.ClearContents nums= Array(1, 1, 2) nums = Arrays.sort(nums) Call permuteHelper(nums) Set dic = Nothing End Sub Public Sub permuteHelper(nums) If path.count = UBound(nums) + 1 Then k = k + 1 s = path(1) & path(2) & path(3) dic(s) = "" Sheet7.Range("a1").Resize(dic.count, 1) = Application.Transpose(dic.Keys) 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