Leetcode!
  • LeetCode!
  • My personal guide to Leetcode
  • Array
    • 11. Container With Most Water
    • 15. 3Sum
    • 219. Contains Duplicate II
    • 238. Product of Array Except Self
    • 245. Shortest Word Distance III
    • 392. Is Subsequence
    • 442. Find All Duplicates in an Array
    • 561. Array Partition I
    • 661. Image Smoother
    • 697. Degree of an Array
    • 723. Candy Crush
    • 832. Flipping an Image
  • Backtracking
    • 294. Flip Game II
    • 401. Binary Watch
    • 1079. Letter Tile Possibilities
  • Binary Search
    • 744. Find Smallest Letter Greater Than Target
    • 852. Peak Index in a Mountain Array
  • String
    • 6. ZigZag Conversion
    • 17. Letter Combinations of a Phone Number
    • 38. Count and Say
    • 521. Longest Uncommon Subsequence I
    • 544. Output Contest Matches
    • 937. Reorder Data in Log Files
  • Design
    • 251. Flatten 2D Vector
    • 281. Zigzag Iterator
  • Hash Table
    • 1. Two Sum
    • 508. Most Frequent Subtree Sum
    • 884. Uncommon Words from Two Sentences
    • 734. Sentence Similarity
  • Linked List
    • 2. Add Two Numbers
  • Unsorted
    • 917. Reverse Only Letters
  • Math
    • 43. Multiply Strings
    • 462. Minimum Moves to Equal Array Elements II
    • 553. Optimal Division
    • 800. Similar RGB Color
  • Greedy
    • 406. Queue Reconstruction by Height
    • 861. Score After Flipping Matrix
  • Tree
    • 701. Insert into a Binary Search Tree
    • 897. Increasing Order Search Tree
  • Divide and Conquer
    • 53. Maximum Subarray
  • Dynamic Programming
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 120. Triangle
    • 198. House Robber
    • 213. House Robber II
    • 303. Range Sum Query - Immutable
    • 518. Coin Change 2
    • 750. Number Of Corner Rectangles
    • 337. House Robber III
  • Depth first search
    • 841. Keys and Rooms
  • Trie
    • 677. Map Sum Pairs
  • Two pointer
    • 42. Trapping Rain Water
Powered by GitBook
On this page
  • Approach 1: Storing row sums using DP
  • Approach 1: Same as above but O(1) space
  1. Dynamic Programming

120. Triangle

Approach 1: Storing row sums using DP

class Solution(object):
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        let = len(triangle)
        dp = [[0] * (i+1) for i in range(let)]
        dp[0][0] = triangle[0][0]
        counter = 2
        for i in range(1, let):
            for j in range(counter):
                if j == 0:
                    dp[i][j] = triangle[i][j] + dp[i-1][j]
                elif j == counter - 1:
                    dp[i][j] = triangle[i][j] + dp[i-1][j-1]
                else:
                    dp[i][j] = triangle[i][j] + min(dp[i-1][j-1], dp[i-1][j])
            counter += 1
        return min(dp[-1])

As like a standard DP problem, we will store the sums up to the previous row and use it to update the next row. The update condition here being: dp[i][j] = triangle[i][j] + min(dp[i-1][j-1], dp[i-1][j]) where (i,j) are the current co-ordinates of the triangle matrix for which the min sum is being evaluated, and dp[i][j] stores the sums up to row i and location j.

d[element] = element + min(d[left_parent], d[right_parent])

Time Complexity: O(N), where N is the total number of numbers in triangle

Space Complexity: O(N)

Approach 1: Same as above but O(1) space

In the above solution it is visible that the for row N we only need information from row N-1 and so on. This way we can optimize memory as below

class Solution(object):
    def minimumTotal(self, triangle):
        """
        https://leetcode.com/problems/triangle/description/
        :type triangle: List[List[int]]
        :rtype: int
        """
        lastRow = triangle[-1]

        for row in reversed(triangle[:-1]):
            tempRow = row[:]
            for i in range(0,len(row)):
                tempRow[i] += min(lastRow[i], lastRow[i+1])
            lastRow = tempRow
        return lastRow[0]

Time Complexity: O(N), where N is the total number of numbers in triangle

Space Complexity: O(n), where n is the number of rows. N = n(n+1)/2

Previous64. Minimum Path SumNext198. House Robber

Last updated 6 years ago