120. Triângulo - Solução JavaScript com explicação
const minimumTotal = function(triangle) {
const len = triangle.length
const map = triangle[len - 1]
/**
* Example: [
* [2],
* [3,4],
* [6,5,7],
* [4,1,8,3]
* ]
* map = [4,1,8,3]
*/
for (let i = len - 2; i >= 0; i--) {
for (let j = 0; j <= i; j++) {
map[j] = Math.min(map[j], map[j + 1]) + triangle[i][j]
/**
* first loop,
* map[0] = Math.min(4 , 1) + 6 = 7
* map[1] = Math.min(1 , 8) + 5 = 6
* map[2] = Math.min(8 , 3) + 7 = 10
*
* second loop,
* map[0] = Math.min(7 , 6) + 3 = 9
* map[1] = Math.min(6 , 10) + 4 = 10
*
* third loop,
* map[0] = Math.min(9 , 10) + 2 = 11
*/
}
}
return map[0]
}
Asiful Islam Sakib