[LeetCode][JavaScript]Triangle
Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
https://leetcode.com/problems/triangle/
动态规划,找个规律。
每一层都基于上一层的最小和来推断当前的最小和。
第一个点的min只能是上层的结果加上自己;最后一个点的min只能是上层的结果加上自己;中间的点就2个选择,上层对应下标的点和(对应下标 - 1)的点。
1 /** 2 * @param {number[][]} triangle 3 * @return {number} 4 */ 5 var minimumTotal = function(triangle) { 6 var passed = triangle[0]; 7 if(triangle.length === 1){ 8 return passed[0]; 9 } 10 var min = Infinity; 11 for(var i = 1; i < triangle.length; i++){ 12 var row = triangle[i]; 13 var currRow = []; 14 for(var j = 0; j < row.length; j++){ 15 var tmp = null; 16 if(j === 0){ 17 tmp = row[0] + passed[0]; 18 }else if(j === row.length - 1){ 19 tmp = row[j] + passed[j - 1]; 20 }else{ 21 tmp = Math.min(row[j] + passed[j], row[j] + passed[j - 1]); 22 } 23 currRow.push(tmp); 24 if(i === triangle.length - 1){ 25 if(tmp < min){ 26 min = tmp; 27 } 28 } 29 } 30 passed = currRow; 31 } 32 return min; 33 };