Topic links
Title Requirements:
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
1 [ [2 ], 3 [3 , 4 ], 4 [6 , 5 , 7 ], 5 [1 , 8 , 3 6 ]
The minimum path sum from top to bottom 11
is (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus Point If-able to does this using only O(n) extra space, where n is the total number of rows in the triangle.
The specific code is as follows:
1 classSolution {2 Public:3 intMinimumtotal (vector<vector<int> > &triangle) {4 introws =triangle.size ();5 if(Rows = =0)6 return 0;7 8 int* DP =New int[rows];9 intSzoflastrow = Triangle[rows-1].size ();Ten for(inti =0; i < Szoflastrow; i++) OneDp[i] = triangle[rows-1][i]; A - for(inti = Rows-2; I >-1; i--) - { the intcols =triangle[i].size (); - for(intj =0; J < cols; J + +) -DP[J] = triangle[i][j] + min (dp[j], dp[j +1]); - } + - returndp[0]; + } A};
View Code
The most central areas of this program are:
1]);
The diagram can be expressed as follows:
An example of this is:
It is important to note that the only change in this example is dp[0],dp[1] and it has not changed.
Leetcode's "Dynamic Planning": Triangle