120. Triangle
package LeetCode_120 /** * 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). * */ class Solution { /* * solution 1: dp, Top-Down, Time:O(n^2),Space:O(n^2) * */ fun minimumTotal(triangle: List<List<Int>>): Int { if (triangle == null || triangle.isEmpty()) { return 0 } val n = triangle.size val dp = Array(n + 1) { IntArray(n + 1) { Int.MAX_VALUE } } for (i in 1..n) {//start from second row for (j in 1..i) {//i elements in row i dp[i][j] = triangle[i - 1][j - 1] if (i == 1 && j == 1) { //in first row, skip it, because just fill the first number continue } if (j == 1) { //in the left most col dp[i][j] += dp[i - 1][j] } else if (j == i) { //in the right most col dp[i][j] += dp[i - 1][j - 1] } else { //in the middle dp[i][j] += Math.min(dp[i - 1][j], dp[i - 1][j - 1]) } } } //result is minimum in last row return Math.min(Int.MAX_VALUE, dp[n].min()!!) } }
Similar:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)