LeetCode304. Range Sum Query 2D - Immutable

题目链接:

https://leetcode.com/problems/range-sum-query-2d-immutable/

题目描述:

求矩阵数组中由左上角点(row1,col1)和右下角点(row2,col2)形成的矩形中所有数字之和。

题目分析:

动态规划的思想。

sums[i][j]=sums[i-1][j]+sums[i][j-1]-sums[i-1][j-1]+matrix[i][j];

代码:

class NumMatrix {
public:
    NumMatrix(vector<vector<int>> &matrix) {
        int row=matrix.size();
        if(row==0){
            return;
        }
        int col=matrix[0].size();
        sums=vector<vector<int>>(row,vector<int>(col,0));
        sums[0][0]=matrix[0][0];
        for(int i=1;i<row;i++){
            sums[i][0]=sums[i-1][0]+matrix[i][0];
        }
        for(int i=1;i<col;i++){
            sums[0][i]=sums[0][i-1]+matrix[0][i];
        }
        for(int i=1;i<row;i++){
            for(int j=1;j<col;j++){
                sums[i][j]=sums[i-1][j]+sums[i][j-1]-sums[i-1][j-1]+matrix[i][j];
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        if(row1>row2 || col1>col2){
            return 0;
        }
        if(row1==0 && col1==0){
            return sums[row2][col2];
        }
        else if(row1==0){
            return sums[row2][col2]-sums[row2][col1-1];
        }
        else if(col1==0){
            return sums[row2][col2]-sums[row1-1][col2];
        }
        else{
            return sums[row2][col2]-sums[row2][col1-1]-sums[row1-1][col2]+sums[row1-1][col1-1];
        }
    }
private:
    vector<vector<int>> sums;
};

你可能感兴趣的:(LeetCode,动态规划)