【LEETCODE】模拟面试-120- Triangle
题目:
https://leetcode.com/problems/triangle/
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.
题意:
Given a triangle, and this problem is to find the minimum sum from top to down layer, at each layer, for each point, it can only sum with its adjacent point.
分析:
Since that when we move to the next layer, the sum depends on the previous layer's choice, and each choice maybe called more than once, so it's better to use Dynamic Programming to deal with it.
If we solve it from top to down, it may require to build 2D matrix. So we can try from down to top.
- Suppose the triangle has n layers.
- We firstly initiate dp as equal to the last layer of triangle, so dp has 1*n dimension.
- Then we move from (n-1)th layer upward, for each movement, we will compare and store the minimum choice for each point in this layer. That is:
- At (n-1)th layer, for each i in this layer, find min(triangle[i]+dp[i], triangle[i]+dp[i+1]), then refresh dp[i] with the result.
- So dp[i] denote that, till current time, when we move from down to current layer, the minimum so far for each point i in this layer.
图例
[Python]
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = triangle[n-1]
for i in range(n-2,-1,-1):
for j in range(i+1):
dp[j] = min( dp[j], dp[j+1] ) + triangle[i][j]
return dp[0]
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- TorchScript使用的注意事项和常见错误
- Scoped 样式穿透
- 你不知道的this(1)
- PyTorch模型转TVM模型全流程记录
- 一次 Node.js http 连接无法复用的问题排查
- 基于UE4/Unity绘制地图基础元素-线(上篇)
- 编码、R 与 Windows (一)
- 【5分钟玩转Lighthouse】Python绘制图表
- Matt Dowle 演讲节选(二)
- 帝国CMS的sitemap.xml设置和生成
- 【推荐】搭建你的免费 R 云端服务器
- ShareX 对接tu.my图床实现截图和图片自动上传
- 【技巧】如何快速按照日期分组
- 为什么 ggplot2 不支持两个 y 轴?
- 宝塔面板或者LNMP下安装php的mongodb扩展