关闭

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

标签: leetcodedp
359人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:604409次
    • 积分:13837
    • 等级:
    • 排名:第940名
    • 原创:803篇
    • 转载:7篇
    • 译文:0篇
    • 评论:120条
    博客专栏