【leetcode】Minimum Path Sum

本文介绍如何使用动态规划解决最小路径和问题,通过构建answer数组并进行更新,最终找到从左上角到右下角的最短路径。

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这道题,只是初始化和更新answer数组的方式不同。

代码如下(Java):

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

 

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3798193.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值