Minimum Path Sum

来源:互联网 发布:兴华软件 编辑:程序博客网 时间:2024/06/02 04:15

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.


Analysis: DP

1. 用一个一位数组dist存储每一步的结果。grid数组第一行可以直接写入dist,其中dist[0] = grid[0][0],其余元素为dist[k] = dist[k] + grid[0][k]。因为第一行元素只能被从其左边的方向访问到,这样便找到了到第一行所有元素的min sum。

2. 从grid数组第二行开始,逐行一次遍历每一个元素。每当遇到第一列的元素时,直接用grid数组中元素与dist数组中元素的结果更新dist数组的第一个元素的值,即dist[0] += grid[i][0],因为第一列的元素只能被在grid数组中位于其上面的元素所访问到。对于其它元素,可按公式计算,dist[j] = MIN(dist[j-1]+grid[i][j], dist[j]+grid[i][j]),其中第一项代表这一步是从左向右走的,而第二项代表是从上往下走的,这样对于每一个cell,所有的情况就都被包含进去了。


public class Solution {    public int minPathSum(int[][] grid) {        int m=grid.length;        if(m==0) return 0;        int n=grid[0].length;        //if(m==1 && n==1) return grid[0][0];                int [] dist = new int[n];        dist[0] = grid[0][0];        for(int k=1; k<n; k++) {            dist[k] = dist[k-1] + grid[0][k];   // 1st row        }                for(int i=1; i<m; i++) {            for(int j=0; j<n; j++) {                if(j==0) dist[j]+=grid[i][j];   // 1st col                else dist[j] = dist[j-1]<=dist[j] ? dist[j-1]+grid[i][j] : dist[j]+grid[i][j];            }        }                return dist[n-1];    }}

0 0
原创粉丝点击