Tc的专栏

待重头,收拾旧山河,朝天阙

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 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];
    }
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/52356257
文章标签: leetcode dp
个人分类: Leetcode Medium
所属专栏: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭