-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpermute-unique.go
More file actions
92 lines (67 loc) · 1.55 KB
/
permute-unique.go
File metadata and controls
92 lines (67 loc) · 1.55 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package array
import (
"strconv"
"fmt"
"sort"
)
func permuteUnique(nums []int) [][]int {
l := len(nums)
res := [][]int{}
if l == 0 {
return res
}
path := []int{}
useMap := map[int]bool{}
inRes := map[string]bool{}
defUniqueArr(nums, l, path, 0, useMap, "", inRes, &res)
path2 := []int{}
useMap2 := map[int]bool{}
res2 := [][]int{}
// 剪枝前要排序
sort.Ints(nums)
defUnique(nums, l, path2, 0, useMap2, &res2)
fmt.Println(len(res), len(res2))
return res
}
func defUniqueArr(nums []int, l int, path []int, depth int, useMap map[int]bool, pathStr string, inRes map[string]bool, res *[][]int) {
if l == depth {
if !inRes[pathStr] {
inRes[pathStr] = true
*res = append(*res, append([]int{}, path...))
}
return
}
for i := 0; i < l; i++ {
if useMap[i] {
continue
}
useMap[i] = true
path = append(path, nums[i])
numIs := strconv.Itoa(nums[i])
pathStr += numIs
defUniqueArr(nums, l, path, depth+1, useMap, pathStr, inRes, res)
useMap[i] = false
path = path[0 : len(path)-1]
pathStr = pathStr[0 : len(pathStr)-len(numIs)]
}
}
func defUnique(nums []int, l int, path []int, depth int, useMap map[int]bool, res *[][]int) {
if l == depth {
*res = append(*res, append([]int{}, path...))
return
}
for i := 0; i < l; i++ {
if useMap[i] {
continue
}
// 剪支条件
if i > 0 && nums[i] == nums[i-1] && useMap[i-1] == false {
continue
}
useMap[i] = true
path = append(path, nums[i])
defUnique(nums, l, path, depth+1, useMap, res)
useMap[i] = false
path = path[0 : len(path)-1]
}
}