题目描述
给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
示例 1:
[[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
解法一:排序 + 回溯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
func permuteUnique(nums []int) [][]int {
n := len(nums)
sort.Ints(nums)
used := make([]bool, n)
var ans [][]int
var tmp []int
var backtracking func(cnt int)
backtracking = func(cnt int) {
if cnt == n {
ans = append(ans, append([]int(nil), tmp...))
return
}
for i := 0; i < n; i++ {
if used[i] || i > 0 && !used[i-1] && nums[i] == nums[i-1] {
continue
}
used[i] = true
tmp = append(tmp, nums[i])
backtracking(cnt + 1)
tmp = tmp[:len(tmp)-1]
used[i] = false
}
}
backtracking(0)
return ans
}
|