-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path120. Triangle.go
93 lines (73 loc) · 1.98 KB
/
120. Triangle.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"math"
)
type cell struct {
x, y int
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func didHitCache(cache map[cell]int, x, y int) bool {
_, didFind := cache[cell{x, y}]
return didFind
}
func fetchNextCells(row []int, index int) []int {
nextCells := []int{}
if index+1 >= len(row) {
nextCells = append(nextCells, index)
} else {
nextCells = append(nextCells, index)
nextCells = append(nextCells, index+1)
}
return nextCells
}
func recursiveTraversal(traingle [][]int, rowIndex, colIndex, curSum int, cache map[cell]int) int {
curSum += traingle[rowIndex][colIndex]
rowIndex++
// if didHitCache(cache, rowIndex, colIndex) {
// fmt.Printf("didHitcache: %v and %v", rowIndex, colIndex)
// return cache[cell{rowIndex, colIndex}]
// }
if rowIndex >= len(traingle) && didHitCache(cache, rowIndex, colIndex) {
if curSum < cache[cell{rowIndex, colIndex}] {
cache[cell{rowIndex, colIndex}] = curSum
return curSum
} else {
return cache[cell{rowIndex, colIndex}]
}
} else if rowIndex >= len(traingle) {
return curSum
} else if didHitCache(cache, rowIndex, colIndex) {
return cache[cell{rowIndex, colIndex}]
}
nextCells := fetchNextCells(traingle[rowIndex], colIndex)
var minRes int = math.MaxInt64
for i := 0; i < len(nextCells); i++ {
minRes = min(recursiveTraversal(traingle, rowIndex, nextCells[i], curSum, cache), minRes)
fmt.Println(minRes)
// A cache to store the minimum value for a given cell.
fmt.Printf("Storing %v and %v ", rowIndex, nextCells[i])
cache[cell{rowIndex, nextCells[i]}] = minRes
}
return minRes
}
func minimumTotal(triangle [][]int) int {
cache := map[cell]int{}
ans := recursiveTraversal(triangle, 0, 0, 0, cache)
fmt.Println(cache)
return ans
}
// -1
// 2 3
// 1 -1 3
func main() {
// traingle := [][]int{{-1}, {2, 3}, {1, -1, -3}}
traingle := [][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}
answer := minimumTotal(traingle)
fmt.Println("traningle : ", answer)
}