leetcode 【 Triangle 】python 实现
题目:
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.
代码:oj测试通过 Runtime: 82 ms
1 class Solution: 2 # @param triangle, a list of lists of integers 3 # @return an integer 4 def minimumTotal(self, triangle): 5 # special case 6 if len(triangle)==0: 7 return 0 8 # dp visit 9 LEVEL = len(triangle) 10 dp = [0 for i in range(LEVEL)] 11 for i in range(LEVEL): 12 for j in range(len(triangle[i])-1,-1,-1): 13 if j==len(triangle[i])-1 : 14 dp[j] = dp[j-1] + triangle[i][j] 15 elif j==0 : 16 dp[0] = dp[0] + triangle[i][0] 17 else: 18 dp[j] = min(dp[j-1],dp[j]) + triangle[i][j] 19 return min(dp)
思路:
典型的动态规划,思路跟Unique Path类似,详情见
http://www.cnblogs.com/xbf9xbf/p/4250359.html
另,这道题还有一个bonus,如何用尽量少的额外空间。
一般的dp思路是,定义一个O(n)的空间,跟三角形等大小的额外空间。
这里只用三角形最底层那一层的大小的空间。
遍历第i层时,利用 dp[1:len(triangle[i])] 的空间存储开始节点到第i层各个节点的最小和。
这里注意:从后往前遍历可以节省数组空间。这是Array的一个常见操作技巧,详情见
http://www.cnblogs.com/xbf9xbf/p/4240257.html
连续刷刷题,能把前后的技巧多关联起来,对代码的能力提升有一定的帮助。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?