Easy understanding solution with C++


  • 0
    W

    I just calculate row sum of each position in Matrix.

    class NumMatrix {
    private:
        vector<vector<int>> rows;
        int m;
        int n;
    public:
        NumMatrix(vector<vector<int>> &matrix) {
        if(matrix.empty()) return ;
        m=matrix.size();
        n=matrix[0].size();
        for(int i=0;i<m;i++)
        {
            vector<int> row(n+1);
            for(int j=0;j<=n;j++)
            {
                if(j==0) row[j]=0;
                else row[j]+=row[j-1]+matrix[i][j-1];
            }
            rows.push_back(row);
        }
        }
    
        int sumRegion(int row1, int col1, int row2, int col2) {
        if(row2>=m||col2>=n||rows.empty()) return 0;
        int res=0;
        for(int i=row1;i<=row2;i++)
            res+=rows[i][col2+1]-rows[i][col1];
        return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.