LeetCode 64. Minimum Path Sum(动态规划)

题目来源:https://leetcode.com/problems/minimum-path-sum/

问题描述

64. 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 minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:

[

  [1,3,1],

  [1,5,1],

  [4,2,1]

]

Output: 7

Explanation: Because the path 1→3→1→1→1 minimizes the sum.

------------------------------------------------------------

题意

给定一个m×n的棋盘矩阵grid,规定只能向右或向下走。矩阵中的每个元素表示费用,求从左上角到右下角的最小费用。

------------------------------------------------------------

思路

同LeetCode 62. Unique Paths(动态规划)和LeetCode 63. Unique Paths II(动态规划),用时间复杂度为O(mn)的动态规划求解,可以直接使用了形参grid作为dp数组。区别只是在于状态转移方程变为:

dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])

------------------------------------------------------------

代码

class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        if (m == 0)
        {
            return 0;
        }
        int n = grid[0].length;
        if (n == 0)
        {
            return 0;
        }
        int i = 0, j = 0;
        for (i=1; i

 

你可能感兴趣的:(LeetCode)