Minimum Path Sum leetcode - Ryan的修炼之路
Given a m x n grid filled with non-negative numbers, find a path from
top left to bottom right which minimizes the sum of all numbers along
its path.Note: You can only move either down or right at any point in time.
二维动态规划
说明
state: dpx从起点走到x,y的最短路径
function: dpx = min(dpx-1, dpx) + costx
intialize: dp0 = cost0
// fi = sum(0,0 -> i,0)
// f0 = sum(0,0 -> 0,i)
answer: fn-1
复杂度
时间O(mn) 空间O(mn)
代码
public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] dp = new int[m][n]; dp[0][0] = grid[0][0]; for (int i = 1; i < n; i++) { dp[0][i] = grid[0][i] + dp[0][i - 1]; } for (int j = 1; j < m; j++) { dp[j][0] = grid[j][0] + dp[j - 1][0]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) {dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } } return dp[m - 1][n - 1];}
一维动态规划
说明
初始化第一行的数据, 然后每次遍历一行覆盖一次数据, 思路与二维相同
复杂度
时间O(m*n) 空间O(n)
代码
public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[] dp = new int[n]; dp[0] = grid[0][0]; for (int i = 1; i < n; i++) { dp[i] = dp[i - 1] + grid[0][i]; } for (int i = 1; i < m; i++) { for (int j = 0; j < n; j++) {if (j != 0) { dp[j] = Math.min(dp[j], dp[j - 1]);}dp[j] += grid[i][j]; } } return dp[n - 1];}