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

原文地址:https://www.cnblogs.com/johnnyzhao/p/14139096.html