c++ solution


  • 0
    B
    class NumMatrix {
    public:
        vector<vector<int>> dp;
        NumMatrix(vector<vector<int>> &matrix) {
            if(!matrix.size()) return;
            
            int m=matrix[0].size(),n=matrix.size();
            for(int i=0;i<n;i++) dp.push_back(vector<int> (m,0));
            
            dp[0][0]=matrix[0][0];
            for(int i=1;i<n;i++) dp[i][0]=dp[i-1][0]+matrix[i][0];
            for(int j=1;j<m;j++) dp[0][j]=dp[0][j-1]+matrix[0][j];
            
            for(int i=1;i<n;i++)
                for(int j=1;j<m;j++)
                    dp[i][j]=dp[i-1][j]-dp[i-1][j-1]+dp[i][j-1]+matrix[i][j];
                    
        }
    
        int sumRegion(int row1, int col1, int row2, int col2) {
            if(!dp.size()) return 0;
            
            if(row1==0 && col1==0) return dp[row2][col2];
            else if(row1==0 && col1>0) return dp[row2][col2]-dp[row2][col1-1];
            else if(row1>0 && col1==0) return dp[row2][col2]-dp[row1-1][col2];
            else return dp[row2][col2]-dp[row2][col1-1]-dp[row1-1][col2]+dp[row1-1][col1-1];
        }
    };
    

Log in to reply
 

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