-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpath-sum-iv.go
More file actions
42 lines (34 loc) · 789 Bytes
/
path-sum-iv.go
File metadata and controls
42 lines (34 loc) · 789 Bytes
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
package main
func pathSum(nums []int) int {
parent := func(pos int) int {
return (pos - 1) / 2
}
lvlOffset := func(lvl int) int {
// expect lvl will be always non-negative
return int((1 << uint(lvl)) - 1)
}
sums := make([]int, lvlOffset(4))
isLeaf := make([]bool, lvlOffset(4))
empty := make([]bool, lvlOffset(4))
for pos := range isLeaf {
isLeaf[pos] = true
empty[pos] = true
}
for _, num := range nums {
lvl, posWithinLvl, val := num/100-1, (num/10)%10-1, num%10
pos := lvlOffset(lvl) + posWithinLvl
curParent := parent(pos)
sums[pos] = val + sums[curParent]
empty[pos] = false
if pos != 0 {
isLeaf[curParent] = false
}
}
result := 0
for pos := range sums {
if !empty[pos] && isLeaf[pos] {
result += sums[pos]
}
}
return result
}