Clean java solution with DP


  • 0
    J
    public class NumMatrix {
    private int[][] res;
    public NumMatrix(int[][] matrix) {
        int row = 2, col = 2;
        if(matrix.length > 0){
            row = matrix.length + 1;
            col = matrix[0].length + 1;
            res = new int[row][col];
            for(int i = 1; i < row; i++){
                for(int j = 1; j < col; j++){
                    res[i][j] = res[i][j - 1] + res[i - 1][j] + matrix[i - 1][j - 1] - res[i - 1][j - 1];
                }
            }
        }else{
            res = new int[row][col];
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        return res[row2 + 1][col2 + 1] - res[row1][col2 + 1] - res[row2 + 1][col1] + res[row1][col1];
    }
    

    }


Log in to reply
 

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