Triangle
In a right angle triangle you can only move down and down right . Find minimum sum
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
Memorization
var minimumTotal = function (triangle) { let n = triangle.length; let dp = Array.from({ length: n }, () => Array(n).fill(undefined)) function recurr(i, j, dp) { if (i == n - 1) { return triangle[i][j] }
if (dp[i][j] !== undefined) {
return dp[i][j]
}
let down = recurr(i + 1, j,dp);
let diaglonal = recurr(i + 1, j + 1,dp);
dp[i][j] = triangle[i][j] + Math.min(down, diaglonal)
return dp[i][j]
}
return recurr(0, 0, dp)
};
Tabulation
All the element in last row are our bases cases, whenever we'll reach the end we'll stop. We'll start from last second row and go down for each row can calculate minimum sum and then move up .
var minimumTotal = function (triangle) {
let n = triangle.length;
let dp = Array.from({ length: n }, () => Array(n).fill(0));
for (let col = 0; col < n; col++) {
dp[n - 1][col] = triangle[n - 1][col]
}
for (let i = n - 2; i >= 0; i--) {
for (let j = 0; j <= i; j++) {
let down = dp[i + 1][j]
let downRight = dp[i + 1][j + 1]
dp[i][j] = triangle[i][j] + Math.min(down, downRight)
}
}
return dp[0][0]
};