全排列||  (数组中有重复的元素)

//递归加回溯
func permuteUnique(nums []int) (ans [][]int) {
    //对数组进行排序
    sort.Ints(nums)
    n := len(nums)
    perm := []int{}

    //标记是否被访问
    vis := make([]bool, n)

    var backtrack func(int)
    backtrack = func(idx int) {
        if idx == n {
            ans = append(ans, append([]int(nil), perm...))
            return
        }

        for i, v := range nums {
            //这个数填过直接continue
           //这个数没填过,但是他前一个数也没填过和当前数和前一个数相等,直接continue
           //重复的数相邻只能算是一种情况
            if vis[i] || i > 0 && !vis[i-1] && v == nums[i-1] {
                continue
            }
            perm = append(perm, v)
            vis[i] = true
            //递归
            backtrack(idx + 1)
            vis[i] = false
            perm = perm[:len(perm)-1]
        }
    }

    backtrack(0)
    return
}


链接:https://leetcode-cn.com/problems/permutations-ii/solution/quan-pai-lie-ii-by-leetcode-solution/