Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,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
}