文章目录
- 题目描述
- 代码 & 题目描述
题目描述
- 动态规划,dp[][]都可以直接用grid[][]。空间复杂度O(1)
代码 & 题目描述
- dp[i[j] = grid[i][j] + (grid[i-1][j] + grid[i][j-1]),注意边界判断
- 时间复杂度O(m*n)
class Solution {public int minPathSum(int[][] grid) {// 一眼dpint m = grid.length;int n = grid[0].length;// dp[i][j]代表(i,j)到终点的最短路径// int[][] dp = new int[m][n];for(int i=m-1;i>=0;i--){for(int j=n-1;j>=0;j--){// 先算上自身// dp[i][j] = grid[i][j];if(i == m-1 && j == n-1){continue;}if(i+1 >= m){grid[i][j] += grid[i][j+1];}else if(j+1 >= n){grid[i][j] += grid[i+1][j];}else{grid[i][j] += Math.min(grid[i+1][j],grid[i][j+1]);}}}return grid[0][0];}
}