47.全排列II
47.全排列II
题解
上一个元素和当前相同,并且没有访问过就跳过
代码
package main import "sort" func permuteUnique(nums []int) [][]int { result := make([][]int, 0) list := make([]int, 0) vis := make([]bool, len(nums)) sort.Ints(nums) backtrack(nums, vis, list, &result) return result } func backtrack(nums []int, vis []bool, list []int, result *[][]int) { if len(list) == len(nums) { ans := make([]int, len(list)) copy(ans, list) *result = append(*result, ans) } for i := 0; i < len(nums); i++ { if vis[i] == false { if i != 0 && nums[i] == nums[i-1] && vis[i-1] == false { continue } vis[i] = true list = append(list, nums[i]) backtrack(nums, vis, list, result) list = list[0 : len(list)-1] vis[i] = false } } }