LeetCode 64 Minimum Path Sum (数字三角形)

原创 2016年08月29日 20:27:58

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.


题目链接:https://leetcode.com/problems/minimum-path-sum/

题目分析:基础的动态规划问题,dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]

public class Solution {
    public int minPathSum(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int[][] dp = new int[n][m];
        for(int i = 0; i < n; i ++) {
            Arrays.fill(dp[i], 0);
        }
        dp[0][0] = grid[0][0];
        for(int i = 0; i < n; i ++) {
            for(int j = 0; j < m; j ++) {
                if(i > 0 && j > 0) {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
                }
                else if(i > 0) {
                    dp[i][j] = dp[i - 1][j] + grid[i][j];
                }
                else if(j > 0) {
                    dp[i][j] = dp[i][j - 1] + grid[i][j];
                }
            }
        }
        return dp[n - 1][m - 1];
    }
}


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

相关文章推荐

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 - 64. Minimum Path Sum

64. Minimum Path Sum Given a m x n gridfilled with non-negative numbers, find a path from top left ...
  • laeen
  • laeen
  • 2017年03月25日 09:57
  • 78

LeetCode 64. Minimum Path Sum 动态规划

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

Leetcode-64. Minimum Path Sum

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

【leetcode】64. Minimum Path Sum

【leetcode】64. Minimum Path Sum

leetcode - 62,63. Unique Paths(II) & 64.Minimum Path Sum

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上264号问题这三个题目的共同之处在于均是二维矩阵上的规划问题问题描述:62 Unique Pa...
  • Quiteen
  • Quiteen
  • 2017年06月11日 20:40
  • 94

LeetCode 64 Minimum Path Sum--In C++

思路: 用动态规划的话,速度是最快的。 状态迁移方程:mat[i][j] = (mat[i][j + 1] 即要找到一个格子的下边和右边较小的值,在加上grid中给他的值,作为mat中这个位置的...

leetcode解题之62&63. Unique Paths ||64. Minimum Path Sum java版(路径(最短)可达)

leetcode解题之62&63. Unique Paths || java版(路径可达) ,63. Unique Paths II ,62. Unique Paths 。64. Minimum Pa...

leetcode 64. 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 64 — Minimum Path Sum(C++ Java Python)

题目:http://oj.leetcode.com/problems/minimum-path-sum/ Given a m x n grid filled with non-negative num...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode 64 Minimum Path Sum (数字三角形)
举报原因:
原因补充:

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