-
Notifications
You must be signed in to change notification settings - Fork 549
/
Copy pathpermutations-ii.go
executable file
·53 lines (40 loc) · 1.11 KB
/
permutations-ii.go
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package Problem0047
import "sort"
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
n := len(nums)
// vector 是一组可能的解答
vector := make([]int, n)
// taken[i] == true 表示 nums[i] 已经出现在了 vector 中
taken := make([]bool, n)
var ans [][]int
makePermutation(0, n, nums, vector, taken, &ans)
return ans
}
// 这个方式和我原来的方式相比,
// 增加了比较的次数
// 但是,减少了切片生成的次数。
// 所以,速度会快一些。
func makePermutation(cur, n int, nums, vector []int, taken []bool, ans *[][]int) {
if cur == n {
tmp := make([]int, n)
copy(tmp, vector)
*ans = append(*ans, tmp)
return
}
used := make(map[int]bool, n-cur)
for i := 0; i < n; i++ {
if !taken[i] && !used[nums[i]] {
used[nums[i]] = true
// 准备使用 nums[i],所以,taken[i] == true
taken[i] = true
// NOTICE: 是 vector[cur]
vector[cur] = nums[i]
makePermutation(cur+1, n, nums, vector, taken, ans)
// 下一个循环中
// vector[cur] = nums[i+1]
// 所以,在这个循环中,恢复 nums[i] 自由
taken[i] = false
}
}
}