博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Triangle
阅读量:7209 次
发布时间:2019-06-29

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

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[     [2],    [3,4],   [6,5,7],  [4,1,8,3]]

 

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

 

Ref:http://www.cnblogs.com/feiling/p/3269609.html

[解题思路]

该题是经典的DP问题,状态可以定义成dp[node]表示从当前node到bottom的最小路径和,对于最下面一层,因为它们是最底层,故它们到bottom的最小路径和就是它们自身;再往上一层,如节点6,它到达bottom的最小路径和即为节点4与节点1之间的最小值加上节点6自身的值

由以上分析得出状态迁移方程:

dp[node] = value[node] + min(dp[child1], dp[child2])

另外本题要求时间复杂度为:O(n), n为三角形的行数

 

逐行扫描,每一个位置能取得的最小sum,是该元素上面两个能取得的最小sum中最小的那一个sum加上自己的值。只需要开一个数组重复利用就行了。

实现的时候,有些繁琐的地方,这个题比较好从下往上扫描。如果从上往下,其中minV的初始值问题就很头疼。

 

public class Solution {    public int minimumTotal(ArrayList
> triangle) { if(triangle == null || triangle.size() == 0){ return 0; } int row = triangle.size(); int[] num = new int[row]; for(int i = row-1; i>= 0; i--){ int col = triangle.get(i).size(); for(int j = 0; j< col; j++){ if(i == row-1){ num[j] = triangle.get(i).get(j); continue; } num[j] = Math.min(num[j] , num[j+1])+ triangle.get(i).get(j); } } return num[0]; }}

 

转载于:https://www.cnblogs.com/RazerLu/p/3552577.html

你可能感兴趣的文章
error C2220: 警告被视为错误 - 没有生成“object”文件
查看>>
IO is frozen on database xxx, No user action is required
查看>>
执行perl xttdriver.pl报错Can't locate Getopt/Long.pm in @INC
查看>>
log4j的最佳实践(转)
查看>>
linux中 jdk 的卸载和安装[转]
查看>>
Install And Configure ColdFusion MX 6.1 on Windows
查看>>
[转]Error: "SQL BPA command line has encountered a problem and needs to close"
查看>>
objective-C 的内存管理之-引用计数
查看>>
如何实现共享软件网络授权认证,包括注册新用户、登录、修改密码等操作
查看>>
通过TextWatcher去观察输入框中输入的内容以及输入字符个数
查看>>
C#窗体控件-单选按钮控件RadioButton
查看>>
[C++]红色波浪线是什么意思
查看>>
tomcat之 JDK8.0安装、tomcat-8.5.15安装
查看>>
Android ADB命令
查看>>
Java调用Lua脚本(热载实现)
查看>>
排除“使用主题 css 文件要求页上有标头控件。(例如 <head runat="server" />)”错误...
查看>>
jdk1.7的新特性
查看>>
关注一下IBM工具
查看>>
JS 英文不截断单词截取
查看>>
Oracle 数据定义
查看>>