首页 > 代码库 > Minimum Path Sum
Minimum Path Sum
https://oj.leetcode.com/problems/minimum-path-sum/
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.
解题思路:
典型的动态规划。将状态dp[m][n]定义为,到该点的sum。dp[m][n] = min{dp[m - 1][n], dp[m][n - 1]} + grid[m][n]。
public class Solution { public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] sum = new int[m][n]; sum[0][0] = grid[0][0]; for(int i = 1; i < n; i++){ sum[0][i] = sum[0][i - 1] + grid[0][i]; } for(int i = 1; i < m; i++){ sum[i][0] = sum[i - 1][0] + grid[i][0]; } for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++){ sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; } } return sum[m - 1][n - 1]; }}
与上一题一样,仍然可以用一个一维数组定义这个dp,以节省空间。sum[j] = Math.min(sum[j], sum[j - 1]) + grid[i][j];sum永远保存本行的sum[j],所以到点[i][j],前一个点的dp[i - 1][j]已更新,比较他和当前dp[j](未更新,代表上一行)的值,然后再更新当前dp[j]。
public class Solution { public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[] sum = new int[n]; sum[0] = grid[0][0]; for(int i = 1; i < n; i++){ sum[i] = sum[i - 1] + grid[0][i]; } for(int i = 1; i < m; i++){ for(int j = 0; j < n; j++){ if(j ==0){ sum[j] = sum[j] + grid[i][j]; }else { sum[j] = Math.min(sum[j], sum[j - 1]) + grid[i][j]; } } } return sum[n - 1]; }}
Minimum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。