LeetCode: Permutations II Posted on January 15, 2018July 26, 2020 by braindenny Permutations II Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #combination, #backtracking Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [ [1,1,2], [1,2,1], [2,1,1] ] Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. // https://code.dennyzhang.com/permutations-ii // Basic Ideas: backtracking // // Complexity: Time O(n!), Space O(1) import "sort" func dfs(combination []int, visited []bool, nums []int, res *[][]int) { if len(combination) == len(nums) { combination2 := make([]int, len(combination)) copy(combination2, combination) *res = append(*res, combination2) return } for i, b := range visited { if b { continue } // avoid duplicated caculation if i>0 && nums[i-1] == nums[i] && ! visited[i-1] { continue } combination = append(combination, nums[i]) visited[i] = true dfs(combination, visited, nums, res) visited[i] = false combination = combination[0:len(combination)-1] } } func permuteUnique(nums []int) [][]int { sort.Ints(nums) res := [][]int{} visited := make([]bool, len(nums)) dfs([]int{}, visited, nums, &res) return res } Post Views: 2