标签:
问题描述: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.
问题分析:参考路径问题,其实就是加权的路径问题,求最小的权值和。动态规划问题,核心递推公式,d[i][j] = min(d[i-1][j],d[i][j-1])+a[i][j].
public class MinPathSum { public int minPathSum(int[][] grid) { for(int i = 1; i < grid.length; i ++)//初始化第一行第一列 { grid[i][0] += grid[i-1][0]; } for(int i = 1; i < grid[0].length; i ++) { grid[0][i] += grid[0][i-1]; } for(int i = 1; i < grid.length; i ++) { for(int j = 1; j < grid[0].length; j ++) { grid[i][j] = Math.min(grid[i-1][j], grid[i][j-1])+grid[i][j];//核心递推公式 } } return grid[grid.length-1][grid[0].length]; } }
标签:
原文地址:http://www.cnblogs.com/masterlibin/p/5775955.html