首页 技术 正文
技术 2022年11月14日
0 收藏 695 点赞 2,480 浏览 1087 个字

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.


题目标签:Array

  这道题目和前面两题差不多,基本思想都是一样的。这题要求我们找到最小和的路径。同样用Dynamic programming,我们可以分析一下,path 只能走右边和下面,那么对于每一个点,它的path 只可能从左边和上面来,我们只要在两者中取一个小的加上自己就可以了。因此,遍历gird,对于每一个点,有四种情况:

  case 1:它有left 和top,取小的加上自己;

  case 2:它只有left,left + 自己;

  case 3:它只有top, top + 自己;

  case 4:它没有left 和top,什么都不需要做。

  最后返回终点的值就可以了。这里可以in-place, 也可以自己新建立一个matrix。

Java Solution:

Runtime beats 35.80%

完成日期:07/22/2017

关键词:Array

关键点:Dynamic Programming, 逆向思考

 public class Solution
{
public int minPathSum(int[][] grid)
{
int rowSize = grid.length;
int colSize = grid[0].length; for(int i=0; i<rowSize; i++) // row
{
for(int j=0; j<colSize; j++) // column
{
// if this point has both left and top
if(j-1 >=0 && i-1 >=0)
grid[i][j] += Math.min(grid[i][j-1], grid[i-1][j]);
else if(j-1 >=0) // if this point only has left
grid[i][j] += grid[i][j-1];
else if(i-1 >=0) // if this point only has top
grid[i][j] += grid[i-1][j];
// else, this point has no left and no top }
} return grid[rowSize-1][colSize-1];
}
}

参考资料:N/A

LeetCode 算法题目列表 – LeetCode Algorithms Questions List

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898