zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    公众号我也快看不下去了
    朋友圈我快看不下去了!
    微信5.2
    微信支付类目及费率
    ACCESS TOKEN
    关于微博认证和微信认证
    重定向
    微信公众账号支付商户接入指南
    微信公众平台开发(94) 违章查询
    [Servlet]什么是Servlet
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14139096.html
Copyright © 2011-2022 走看看