【Leeetcode】304. Range Sum Query 2D - Immutable

class NumMatrix(object):
    """
    we need two steps to solve this question
    step:
    calc out the acreage of rectangle whose top left point is origin and bottom right point is (i,j)
    we need use dynamic programming to get the matrix
    dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1](dp[i-1][j-1] is extra area add to the result)
    """

    def __init__(self, matrix):
        """
        :type matrix: List[List[int]]
        """
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return

        self.dp = [[0 for j in range(len(matrix[0])+1)] for i in range(len(matrix)+1)]

        for i in range(1,len(self.dp)):
            for j in range(1, len(self.dp[0])):
                self.dp[i][j] += self.dp[i-1][j] + self.dp[i][j-1] - self.dp[i-1][j-1] + matrix[i-1][j-1]

    def sumRegion(self, row1, col1, row2, col2):
        """
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """
        return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]

相关文章:

  • 2021-06-18
  • 2021-12-29
  • 2021-06-21
  • 2019-05-16
  • 2021-07-05
  • 2018-11-26
  • 2021-12-15
  • 2021-04-20
猜你喜欢
  • 2021-12-05
  • 2022-01-20
  • 2020-02-11
  • 2021-10-31
  • 2021-11-23
  • 2021-12-25
相关资源
相似解决方案