/
main.go
68 lines (60 loc) · 1.06 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"sort"
)
/*
{
from:"https://leetcode-cn.com/problems/permutations-ii",
reference:[],
description:"全排列 II",
solved:true,
}
*/
type Set struct {
content map[interface{}]bool
}
func NewSet() *Set {
return &Set{
content: map[interface{}]bool{},
}
}
func (s *Set) Add(value interface{}) {
s.content[value] = true
}
func (s *Set) Has(value interface{}) bool {
_, ok := s.content[value]
return ok
}
func permuteUnique(nums []int) [][]int {
var res [][]int
var l = len(nums)
sort.Ints(nums)
var backTrack func(first int)
backTrack = func(first int) {
if first == l {
res = append(res, append([]int{}, nums...))
return
}
var set = NewSet()
set.Add(nums[first])
for i := first; i < l; i++ {
if i != first {
if set.Has(nums[i]) {
continue
}else{
set.Add(nums[i])
}
}
nums[i], nums[first] = nums[first], nums[i]
backTrack(first + 1)
nums[i], nums[first] = nums[first], nums[i]
}
}
backTrack(0)
fmt.Println(res)
return res
}
func main() {
permuteUnique([]int{1,2,3,4})
}