0%

LeetCode-304

题目

结果

代码

直接进行一波动态规划

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
type NumMatrix struct {
sums [][]int
}

func Constructor(matrix [][]int) NumMatrix {
if len(matrix) == 0 {
return NumMatrix{}
}
sums := make([][]int, len(matrix)+1)
for i := range sums {
sums[i] = make([]int, len(matrix[0])+1)
}

for i, nums := range matrix {
for j, v := range nums {
sums[i+1][j+1] += sums[i][j+1] + sums[i+1][j] - sums[i][j] + v
}
}
fmt.Println(sums)
return NumMatrix{sums}
}

func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
return this.sums[row2+1][col2+1] - this.sums[row2+1][col1] - this.sums[row1][col2+1] + this.sums[row1][col1]
}

/**
* Your NumMatrix object will be instantiated and called as such:
* obj := Constructor(matrix);
* param_1 := obj.SumRegion(row1,col1,row2,col2);
*/