120. Triangle

Medium

Given a triangle array, return the minimum path sum from top to bottom.

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

Example 1:

Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output:
 11
Explanation:
 The triangle looks like:
   2
  3 4
 6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).

Example 2:

Input: triangle = [[-10]]
Output:
 -10

Constraints:

  • 1 <= triangle.length <= 200

  • triangle[0].length == 1

  • triangle[i].length == triangle[i - 1].length + 1

  • -104 <= triangle[i][j] <= 104

Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?

解題

func minimumTotal(triangle [][]int) int {
    if len(triangle) == 1 {
        return triangle[0][0]
    }

    for i := 1; i < len(triangle); i++ {
        for j := 0; j < len(triangle[i]); j++ {
            if j == 0 {
                triangle[i][j] += triangle[i - 1][0]
            } else if j == i {
                triangle[i][j] += triangle[i - 1][j - 1]
            } else {
                triangle[i][j] += min(triangle[i - 1][j], triangle[i - 1][j - 1])
            }
        }
    }

    res := triangle[len(triangle) - 1][len(triangle) - 1]
    for i := 0; i < len(triangle); i++ {
        if triangle[len(triangle) - 1][i] < res {
            res = triangle[len(triangle) - 1][i]
        }
    }

    return res
    
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

討論區發現的漂亮解答,和我的方法相反,是從下往上,最後回傳 triangle[0][0] 即可。

func minimumTotal(triangle [][]int) int {
    for i := len(triangle) - 2; i >= 0; i-- {
        for j := 0; j < len(triangle[i]); j++ {
           triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j + 1])
        }
    }

    return triangle[0][0]
}

func min(a,b int) int {
    if a < b {
        return a
    }
    return b
}

Last updated