120. Triangle #2214
-
Topics: Given a For each step, you may move to an adjacent number of the row below. More formally, if you are on index Example 1:
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above) Example 2:
Constraints:
Follow up: Could you do this using only |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the minimum path sum from the top to the bottom of a given triangle array. Each step allows moving to an adjacent number in the row below, either to the same index or the next index. The goal is to compute the minimum sum efficiently using dynamic programming with optimal space complexity. Approach
Let's implement this solution in PHP: 120. Triangle <?php
/**
* @param Integer[][] $triangle
* @return Integer
*/
function minimumTotal($triangle) {
$n = count($triangle);
for ($i = $n - 2; $i >= 0; $i--) {
for ($j = 0; $j <= $i; $j++) {
$triangle[$i][$j] += min($triangle[$i + 1][$j], $triangle[$i + 1][$j + 1]);
}
}
return $triangle[0][0];
}
// Test cases
// Example 1
$triangle1 = [[2],[3,4],[6,5,7],[4,1,8,3]];
echo minimumTotal($triangle1) . "\n"; // Output: 11
// Example 2
$triangle2 = [[-10]];
echo minimumTotal($triangle2) . "\n"; // Output: -10
?> Explanation:
This approach efficiently computes the minimum path sum by leveraging dynamic programming principles and minimizes space usage by modifying the input triangle in place. The time complexity is O(n2), where n is the number of rows, which is optimal for this problem. |
Beta Was this translation helpful? Give feedback.
We need to find the minimum path sum from the top to the bottom of a given triangle array. Each step allows moving to an adjacent number in the row below, either to the same index or the next index. The goal is to compute the minimum sum efficiently using dynamic programming with optimal space complexity.
Approach