47. Permutations II ⭐

Medium
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

解題

回圈內第一個 if 的 !visited[i - 1] 其實是代表該值已經被處理過,狀態回復了
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
​
ans := make([][]int, 0)
perm := make([]int, len(nums))
visited := make([]bool, len(nums)) // 一個狀態變量儲存整個狀態樹
​
var backtracking func(int)
backtracking = func(index int) {
if index == len(nums) {
ans = append(ans, append([]int{}, perm...))
return
}
​
for i:=0; i<len(nums); i++ {
if i > 0 && nums[i] == nums[i - 1] && !visited[i - 1] {
continue
}
if !visited[i] {
visited[i] = true
perm[index] = nums[i]
backtracking(index+1)
visited[i] = false // 撤銷選擇
}
}
}
​
backtracking(0)
​
return ans
}