Sponsored
Sponsored
In this approach, we'll use dynamic programming (DP) to achieve the solution. We'll start from the bottom of the triangle and minimize the sum path to the top. We'll keep updating the path sum in a DP array as we move to the top row.
Time Complexity: O(n^2)
, where n
is the number of rows in the triangle.
Space Complexity: O(n)
, due to the use of the array dp
.
1def minimumTotal(triangle):
2 dp = triangle[-1]
3 for row in range(len(triangle) - 2, -1, -1):
4 for col in range(len(triangle[row])):
5 dp[col] = triangle[row][col] + min(dp[col], dp[col + 1])
6 return dp[0]
7
8triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]
9print(minimumTotal(triangle))
The Python function minimumTotal
utilizes dynamic programming to track the minimum path sum from bottom to top. The input triangle gets updated iteratively via the variable dp
which represents the current base row in the triangle.
This approach uses a top-down strategy with memoization to store already computed results, avoiding redundant calculations. Each recursive call stores the minimum path sum starting from the current index down to the base of the triangle.
Time Complexity: O(n^2)
(due to memoization)
Space Complexity: O(n^2)
for memoization storage.
1#
This C code applies a memoization approach, leveraging recursion through dfs
to calculate and store intermediate results in memo
, exploring both potential paths per cell.