LeetCode.64 Minimum Path Sum

来源:互联网 发布:园林设计做题软件 编辑:程序博客网 时间:2024/06/13 11:05

题目:

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.

分析:

class Solution {    public int minPathSum(int[][] grid) {        //从左上角到右下角,给出路径权值最小的路径        //类似triangle求最小路径,但是这里规定了起点和终点        int [][] cur=grid;        //最左边和最上边赋值        for (int i = 1; i < grid[0].length; i++) {            //上边            cur[0][i]+=cur[0][i-1];        }        for (int i = 1; i < grid.length; i++) {            //左边            cur[i][0]+=cur[i-1][0];        }        for(int i=1;i<grid.length;i++){            //动态规划三要素:问题的阶段,每个阶段的状态以及从前一个阶段转化到后一个阶段之间的递推关系            for(int j=1;j<grid[i].length;j++){                //递推关系                cur[i][j]=Math.min(cur[i-1][j],cur[i][j-1])+grid[i][j];            }        }        return cur[grid.length-1][grid[0].length-1];    }}



原创粉丝点击