leetcode -- Minimum Path Sum

本文详细解析了一种寻找矩阵中从左上角到右下角的最小路径和的算法,该算法通过动态规划的方法,利用sum数组存储子问题的解,最终返回整个问题的最小路径和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

[解题思路]

Unique Paths类似,只是把求路径数改成求最小路径和

目标函数:

sum[i][j] = grid[i][j] + Math.min(sum[i+1][j], sum[i][j+1]);

这里为了方便,sum数组分配了[m+2][n+2]个元素,1<=i<=m, 1<=j<=n中存储子问题的解

 1 public int minPathSum(int[][] grid) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int m = grid.length;
 5         int n = grid[0].length;
 6         int[][] sum = new int[m+2][n+2];
 7         for(int i = 0; i < m + 2; i++){
 8             for(int j = 0; j < n + 2; j++){
 9                 sum[i][j] = Integer.MAX_VALUE;
10             }
11         }
12         sum[m][n+1] = 0;
13         for(int i = m; i >= 1; i--){
14             for(int j = n; j >= 1; j--){
15                 sum[i][j] = grid[i-1][j-1] + Math.min(sum[i+1][j], sum[i][j+1]);
16             }
17         }
18         return sum[1][1];
19     }

 

转载于:https://www.cnblogs.com/feiling/p/3271607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值