Given a triangle, find the minimum path sum from top to bottom. Each step of the 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 one (i.e., 2 + 3 + 5 + 1 = 11).
Note:bonus Point If you be able to does this using only O(n) extra space, where n is the total Number of rows in the triangle.
Analytical:
The purpose of this subject is to give a triangular matrix, and the minimum path is obtained. Only one integer can be selected per layer, and the integers on the previous and next levels must be contiguous.
Ideas:
- Dynamic planning: The minimum path length to the K-vertex of layer I is expressed as f (i,j), then:
F (i,j) = min{f (i,j + 1), f (i + 1, j + 1)}+ (I,J)
- The main concern is that space complexity should not exceed N.
- Note the boundary conditions-the first and last elements in each row have only one neighbor in the previous line. The other intermediate elements have two adjacent elements in the previous row.
Algorithm implementation code:
Class Solution {Public:int minimumtotal (vector<vector<int> > &triangle) { int len = triangle.size () for (int i = len-2; I >= 0, i--) for (int j = 0; J < i + 1; ++j) {if (Triangle[i+1][j] > Triangle[i+1][j+1]) {Trian GLE[I][J] + = triangle[i+1][j+1];} ELSE{TRIANGLE[I][J] + = Triangle[i+1][j];}} return triangle[0][0];};
"Leetcode" Triangle (#120)