LeetCode题解——Minimum Path Sum

原创 2015年11月18日 20:36:45

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.

解题思路:动态规划,p[i][j]表示从grid[0][0]到grid[i][j]的最小距离。p[i][j] = min(p[i-1][j] , p[i][j-1]) + grid[i][j]

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(!grid.size()) return 0;
        int m = grid.size(), n = grid[0].size();
        int p[m][n];
        p[0][0] = grid[0][0];
        for(int i=1 ;i<m;i++){
            p[i][0]=p[i-1][0]+grid[i][0];
        }
        for(int j=1; j<n;j++){
            p[0][j]=p[0][j-1]+grid[0][j];
        }
        for(int i=1; i<m; i++){
            for(int j=1; j<n; j++){
                p[i][j] = min(p[i][j-1],p[i-1][j])+grid[i][j];
            }
        }
        return p[m-1][n-1];
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode刷题(C++)——Minimum Path Sum(Medium)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode题解——Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su...

Leetcode64 Minimum Path Sum

Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to...

leetcode[63] Minimum Path Sum 动态规划

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode 1.Minimum Path Sum 2.Unique Paths I and II

大家好,我是刘天昊,快到端午节了,今天说两道动态规划的题目(话说动规真的挺难的) 当然这三题是一样的解体思路先看Unique Paths  A robot is located a...

LeetCode: Minimum Path Sum [063]

【题目】 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom righ...

leetcode笔记:Minimum Path Sum

题目的大意是,给定一个m*n的网格,每个格子里有一个非负整数,找到一条从左上角到右下角的路径,使其经过的格子数值之和最小,每一步只能向右或向下走。可使用动态规划来解决该问题。...

leetcode Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode Solutions : Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...
  • lviiii
  • lviiii
  • 2014年08月11日 13:55
  • 492

Leetcode: Minimum Path Sum

题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode题解——Minimum Path Sum
举报原因:
原因补充:

(最多只允许输入30个字)