public int maxValue(int[][] grid) { //动态规划 int m = grid.length; int n = grid[0].length; for(int i = 1;i<n;i++){ grid[0][i] = grid[0][i] + grid[0][i-1]; } for(int i = 1;i<m;i++){ grid[i][0] = grid[i][0] + grid[i-1][0]; } for(int i = 1;i<m;i++){ for(int j = 1;j<n;j++){ grid[i][j] = Math.max(grid[i-1][j],grid[i][j-1]) + grid[i][j]; } } return grid[m-1][n-1]; }
class Solution { public int maxValue(int[][] grid) { if(grid.length == 0 || grid[0].length == 0){ return 0; } int[][] log = new int[grid.length][grid[0].length]; return dfs_47(grid,log,0,0); } private int dfs_47(int[][] grid, int[][] log, int row, int col) { if(row == grid.length -1 && col == grid[0].length-1){ return grid[row][col]; } if(row>=grid.length || col>=grid[0].length){ return 0; } if(log[row][col] > 0){ return log[row][col]; } int right = dfs_47(grid,log,row,col + 1); int down = dfs_47(grid,log,row+1,col); int max = Math.max(right,down) + grid[row][col]; log[row][col] = max; return max; } }