Leetcode - Paint Fence
Leetcode - Majority Element

Leetcode - Triangle

violet posted @ May 06, 2020 07:51:29 AM in 算法 with tags Algorithm Golang DP , 199 阅读

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).

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.

 

func minimumTotal(nums [][]int) int {
    if len(nums) == 0 {
        return 0
    }
    n := len(nums)
    dp := make([][]int, n)
    for i := 0; i < len(dp); i++ {
        dp[i] = make([]int, i+1)
    }
    dp[0][0] = nums[0][0]
    for i := 1; i < n; i++ {
        for j := 0; j < len(dp[i]); j++ {
            if j != 0 && j != len(dp[i])-1 {
                dp[i][j] = nums[i][j] + min(dp[i-1][j-1], dp[i-1][j])
            } 
            if j == 0 {
                dp[i][j] = nums[i][j] + dp[i-1][j]
            }
            if j == len(dp[i])-1 {
                dp[i][j] = nums[i][j] + dp[i-1][j-1]
            }
        }
    }
    //fmt.Println("dp: ", dp)
    return min(dp[n-1]...)
}

func min(nums ...int) int {
    minNum := nums[0]
    for _, n := range nums {
        if minNum > n {
            minNum = n
        }
    }
    return minNum
}
Parul 说:
Nov 07, 2021 02:45:44 PM
I'm pleased to report that it's an intriguing article to peruse. bangaloreescort harkirankaur udaipurcallgirls trishagupta sexygirlsescorts selectescortsmumbai ranikali nightangels nehasharma Your exposition showed me a new thing, and I believe you're working really hard. Keep doing awesome.
 

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter