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])Approach 1: Same as above but O(1) space
Last updated