给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2] 输出: [[1,1,2], [1,2,1], [2,1,1]]
示例 2:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
题解:
回溯法:
func permuteUnique(nums []int) [][]int {
var path []int
var result [][]int
var backtracking func(nums []int)
var used = make(map[int]bool, len(nums))
backtracking = func(nums []int) {
if len(nums) == len(path) {
tmp := make([]int, len(path))
copy(tmp, path)
result = append(result, tmp)
return
}
for i := 0; i < len(nums); i++ {
if i > 0 && nums[i] == nums[i-1] && !used[i-1] {
continue
}
if used[i] {
continue
}
used[i] = true
path = append(path, nums[i])
backtracking(nums)
used[i] = false
path = path[:len(path)-1]
}
}
sort.Ints(nums)
backtracking(nums)
return result
}
评论前必须登录!
注册