120-triangle

Try it on leetcode

Description

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?

Solution(Python)

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        return self.bottomupdplessspace(triangle)

    # Time complexity: O(2^n)
    # space Complexity: O(n)
    def bruteforce(self, triangle: List[List[int]]) -> int:
        n = len(triangle)

        min_sum = 0

        def dfs(i, j, sum_so_far):
            if i == n:
                return sum_so_far

            return min(
                dfs(i + 1, j, sum_so_far + triangle[i][j]),
                dfs(i + 1, j + 1, sum_so_far + triangle[i][j]),
            )

        return dfs(0, 0, 0)

    # Time complexity: O(n^2)
    # space Complexity: O(n^2)
    def topdowndp(self, triangle: List[List[int]]) -> int:
        n = len(triangle)

        @cache
        def dfs(i, j):
            if i == n - 1:
                return triangle[i][j]

            return triangle[i][j] + min(dfs(i + 1, j), dfs(i + 1, j + 1))

        return dfs(0, 0)

    # Time complexity: O(n^2)
    # space Complexity: O(n^2)
    def bottomupdp(self, triangle: List[List[int]]) -> int:
        n = len(triangle)
        dp = [[float("inf")] * (i) for i in range(1, n + 1)]
        dp[n - 1] = triangle[n - 1]
        for i in range(n - 2, -1, -1):
            for j in range(i + 1):
                dp[i][j] = triangle[i][j] + min(dp[i + 1][j], dp[i + 1][j + 1])
        return dp[0][0]

    # Time complexity: O(n^2)
    # space Complexity: O(n)
    def bottomupdplessspace(self, triangle: List[List[int]]) -> int:
        n = len(triangle)

        if not n:
            return 0

        if n == 1:
            return triangle[0][0]

        dp = [float("inf")] * (n - 1)
        prev_state = triangle[n - 1]

        for i in range(n - 2, -1, -1):
            for j in range(i + 1):
                dp[j] = triangle[i][j] + min(prev_state[j], prev_state[j + 1])
            prev_state = dp

        return dp[0]