题目描述
template
样例
struct NumMatrix {
s : Vec<Vec<i32>>
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl NumMatrix {
fn new(matrix: Vec<Vec<i32>>) -> Self {
let m = matrix.len();
let n = matrix[0].len();
let mut s = vec![vec![0; n+1]; m+1];
for i in 1..m+1 {
for j in 1..n+1 {
s[i][j] = s[i-1][j] + s[i][j-1] -s[i-1][j-1] + matrix[i-1][j-1];
}
}
Self{
s : s
}
}
fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 {
let x1 = (row1+1) as usize;
let y1 = (col1+1) as usize;
let x2 = (row2+1) as usize;
let y2 = (col2+1) as usize;
self.s[x2][y2] - self.s[x1-1][y2] - self.s[x2][y1-1] + self.s[x1-1][y1-1]
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* let obj = NumMatrix::new(matrix);
* let ret_1: i32 = obj.sum_region(row1, col1, row2, col2);
*/