博客
关于我
LeetCode 64. Minimum Path Sum
阅读量:115 次
发布时间:2019-02-26

本文共 1205 字,大约阅读时间需要 4 分钟。

一 题目

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.

Example:

Input:[  [1,3,1],  [1,5,1],  [4,2,1]]Output: 7Explanation: Because the path 1→3→1→1→1 minimizes the sum.

二 分析

medium 级别,题目要求:从二维 数组的左上角到右下角,所有可能的路径中,求经过的元素和最小值。我一开始看以为要使用贪婪算法求右面或者下面的最小值,再看题目元素例子,局部最优解不一定是全局最优解。所以这种方法不行。因为是连着做完一个类型的62,63 的动态规划。所以趁热打铁有连贯性,不然还真懵逼了。这个题目跟之前的 , 类似。

一个解题思路:考虑使用动态规划,我们创建一个二维数组dp,行列数与题目的grid 保持一致。每个位置的值记录了由起始位置(左上角grid[0][0])到此位置的最短距离.

状态转移方程:因为只能右移跟下移,所以 dp[i][j]= min(左面,上面)+grid[i][j].另外特殊情况要提前赋值,比如第一行和第一列,其中第一行的位置只能从左边过来,第一列的位置从能从上面过来。

  代码如下:

public static void main(String[] args) {		int[][] grid ={				{1,3,1},				{1,5,1},				{4,2,1}		};		int res =	minPathSum(grid);		System.out.println(res);	}	public static int minPathSum(int[][] grid) {				int m = grid.length;		int n = grid[0].length;				int[][] dp = new int[m][n];		dp[0][0] = grid[0][0];				//初始化第0列		for(int i=1;i

Runtime: 2 ms, faster than 90.08% of Java online submissions for Minimum Path Sum.

Memory Usage: 42.4 MB, less than 82.43% of Java online submissions forMinimum Path Sum.

转载地址:http://ordy.baihongyu.com/

你可能感兴趣的文章
ndk-cmake
查看>>
NdkBootPicker 使用与安装指南
查看>>
ndk特定版本下载
查看>>
NDK编译错误expected specifier-qualifier-list before...
查看>>
Neat Stuff to Do in List Controls Using Custom Draw
查看>>
Necurs僵尸网络攻击美国金融机构 利用Trickbot银行木马窃取账户信息和欺诈
查看>>
Needle in a haystack: efficient storage of billions of photos 【转】
查看>>
NeHe OpenGL教程 07 纹理过滤、应用光照
查看>>
NeHe OpenGL教程 第四十四课:3D光晕
查看>>
Neighbor2Neighbor 开源项目教程
查看>>
neo4j图形数据库Java应用
查看>>
Neo4j图数据库_web页面关闭登录实现免登陆访问_常用的cypher语句_删除_查询_创建关系图谱---Neo4j图数据库工作笔记0013
查看>>
Neo4j图数据库的介绍_图数据库结构_节点_关系_属性_数据---Neo4j图数据库工作笔记0001
查看>>
Neo4j图数据库的数据模型_包括节点_属性_数据_关系---Neo4j图数据库工作笔记0002
查看>>
Neo4j安装部署及使用
查看>>
Neo4j电影关系图Cypher
查看>>
Neo4j的安装与使用
查看>>
Neo4j(1):图数据库Neo4j介绍
查看>>
Neo4j(2):环境搭建
查看>>
Neo4j(3):Neo4j Desktop安装
查看>>