[LeetCode]64. Minimum Path Sum

来源:互联网 发布:下载输入法软件 编辑:程序博客网 时间:2024/06/16 06:52

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.

Example 1:
[[1,3,1],
[1,5,1],
[4,2,1]]

Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

代码

class Solution {public:    int a[500][500]={0};//到a[i][j]的最短距离    int minPathSum(vector<vector<int>>& grid) {        int w = grid.size();        int h = grid[0].size();        a[0][0] = grid[0][0];        for(int i = 0; i<w;++i)            for(int j = 0; j<h;++j)                if(!(i == 0 && j == 0))                    if( i == 0)                        a[i][j] = a[i][j-1] + grid[i][j];                    else if(j == 0)                        a[i][j] = a[i-1][j] + grid[i][j];                    else                        a[i][j] = min(a[i-1][j],a[i][j-1])+grid[i][j];        return a[w-1][h-1];    }};

代码分析

很基础的动态规划题目。
到某点的距离最短,则在所有前一步里取得最短的再加上当前value。
即可以得到递推公式
f(i,j) = min(f(i-1,j),f(i,j-1))+grid(i,j)
题目中即为上方一格和左方一格中选取较小的。
注意当在第一行和第一列的时候要考虑边界情况

原创粉丝点击