Clean simple yet best submission in C++


  • 1
    class NumMatrix {
    private:
        vector<vector<int>> sums;
    public:
        NumMatrix(vector<vector<int>> &matrix) 
        {
            int rowSize = matrix.size();
            if(!rowSize) return ;
            int colSize = matrix[0].size();
            sums = vector<vector<int>>(rowSize, vector<int>(colSize, 0));
            partial_sum(matrix[0].begin(), matrix[0].end(), sums[0].begin());
            for(int r = 1; r < rowSize; ++r)
            {
                partial_sum(matrix[r].begin(), matrix[r].end(), sums[r].begin());
                for(int c = 0; c < colSize; ++c)
                    sums[r][c] += sums[r-1][c];
            }
        }
    
        int sumRegion(int row1, int col1, int row2, int col2) {
            return sums[row2][col2]+(row1>0 && col1>0? sums[row1-1][col1-1] : 0) - 
                (row1>0? sums[row1-1][col2] : 0) - (col1>0? sums[row2][col1-1] : 0);
        }
    };

Log in to reply
 

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