Leetcode Note: Triangle
I. Description
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.
Ii. Question Analysis
Use Dynamic Planning. Set From topiThekThe minimum path length of each vertex is expressedf(i, k), Thenf(i, k) = min{f(i-1,k), f(i-1,k-1)} + d(i, k), Whered(i, k)Indicates the element of column k of row I in the original triangle array. Then we can obtain from the first row to the finallength-1RowkMinimum path length of each element, and then comparelength-1The path length of all elements in the row, and the minimum value is obtained.
Note the boundary condition that the first and last elements in each row have only one neighbor in the previous row. Other intermediate elements have two adjacent elements in the previous line.
Iii. Sample Code
class Solution {public: int minimumTotal(vector
> &triangle) { vector< vector
>::size_type length = triangle.size(); if(length == 0){ return 0; } int i, j; for(i=1;i
::size_type length_inner = triangle[i].size(); for(j=0;j