type MatMulNode struct { Left any Right any } func MatMulTree(rows []int) any { n := len(rows) - 1 if n < 1 { return nil } var ( costs = make([]int, n*n) splits = make([]int, n*n) ) for add := 1; add < n; add++ { for lo := 0; lo < n-add; lo++ { var ( hi = lo + add outer = rows[lo] * rows[hi+1] min = int(^uint(0) >> 1) split int ) for i := lo + 1; i <= hi; i++ { cost := outer * rows[i] cost += costs[lo*n+i] cost += costs[i*n+hi] if min > cost { min = cost split = i } } i := lo*n + hi costs[i] = min splits[i] = split } } var tree func(lo, hi int) any tree = func(lo, hi int) any { if lo == hi { return lo } i := splits[lo*n+hi] return &MatMulNode{ Left: tree(lo, i-1), Right: tree(i, hi), } } return tree(0, n-1) }
To receive a hint, submit unfixed code.