forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
54 lines (53 loc) · 914 Bytes
/
Solution.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
func recoverArray(n int, sums []int) []int {
m := -slices.Min(sums)
rbt := redblacktree.NewWithIntComparator()
merge := func(key int, value int) {
if v, ok := rbt.Get(key); ok {
nxt := v.(int) + value
if nxt == 0 {
rbt.Remove(key)
} else {
rbt.Put(key, nxt)
}
} else {
rbt.Put(key, value)
}
}
for _, x := range sums {
merge(x+m, 1)
}
ans := make([]int, n)
merge(ans[0], -1)
ans[0] = rbt.Left().Key.(int)
for i := 1; i < n; i++ {
for j := 0; j < 1<<i; j++ {
if j>>(i-1)&1 == 1 {
s := 0
for k := 0; k < i; k++ {
if j>>k&1 == 1 {
s += ans[k]
}
}
merge(s, -1)
}
}
ans[i] = rbt.Left().Key.(int)
}
for i := 0; i < 1<<n; i++ {
s := 0
for j := 0; j < n; j++ {
if i>>j&1 == 1 {
s += ans[j]
}
}
if s == m {
for j := 0; j < n; j++ {
if i>>j&1 == 1 {
ans[j] = -ans[j]
}
}
break
}
}
return ans
}