47. Permutations II #
Problem #
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Main Idea of the Problem #
Given a sequence that may contain duplicate numbers, return all unique permutations.
Solution Approach #
- This problem is an enhanced version of Problem 46. In Problem 46, we find the permutations of an array whose elements are not duplicated. But in this problem, the array elements may be duplicated, so the final permutation results need to be deduplicated.
- The deduplication method is classic logic: after sorting the array, determine duplicate elements and then perform logical checks.
- The other ideas are exactly the same as Problem 46; just use DFS.
Code #
package leetcode
import "sort"
func permuteUnique(nums []int) [][]int {
if len(nums) == 0 {
return [][]int{}
}
used, p, res := make([]bool, len(nums)), []int{}, [][]int{}
sort.Ints(nums) // This is the key logic for deduplication
generatePermutation47(nums, 0, p, &res, &used)
return res
}
func generatePermutation47(nums []int, index int, p []int, res *[][]int, used *[]bool) {
if index == len(nums) {
temp := make([]int, len(p))
copy(temp, p)
*res = append(*res, temp)
return
}
for i := 0; i < len(nums); i++ {
if !(*used)[i] {
if i > 0 && nums[i] == nums[i-1] && !(*used)[i-1] { // This is the key logic for deduplication
continue
}
(*used)[i] = true
p = append(p, nums[i])
generatePermutation47(nums, index+1, p, res, used)
p = p[:len(p)-1]
(*used)[i] = false
}
}
return
}