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:

931. Minimum Falling Path Sum

posted @   johnny_zhao  阅读(111)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示