[Leetcode] Minimum Path Sum

本文介绍如何使用动态规划算法解决最小路径和问题。在给定的m x n网格中,从左上角到右下角的路径中,找到使得路径上所有数字之和最小的路径。

摘要生成于 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.

Solution: dp

 1 public class Solution {
 2     public int minPathSum(int[][] grid) {
 3         int M=grid.length;
 4         int N=grid[0].length;
 5         int[][] dp=new int[M][N];
 6         dp[0][0]=grid[0][0];
 7         for(int i=1;i<M;++i){
 8             dp[i][0]=dp[i-1][0]+grid[i][0];
 9         }
10         for(int i=1;i<N;++i){
11             dp[0][i]=dp[0][i-1]+grid[0][i];
12         }
13         for(int i=1;i<M;++i){
14             for(int j=1;j<N;++j){
15                 dp[i][j]=Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
16             }
17         }
18         return dp[M-1][N-1];
19     }
20 }

 

转载于:https://www.cnblogs.com/Phoebe815/p/4048646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值