Problem:
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 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.
Hide TagsArray Dynamic ProgrammingTest instructions: Give a triangular matrix (bottom-left), top to bottom, each time traversing the adjacent elements between two rows, the minimum path and
Thinking:
Investigate DP, open an array of size of n (the size of the last line of the triangular matrix), each time a row to the next line with that element as the end of the path and,
In this way, finding the smallest element in the array at the end is the smallest path and
Code
Class Solution {public: int minimumtotal (vector<vector<int> > &triangle) { if (triangle.size ( ) = = 0) return 0; Vector<int> f (triangle[triangle.size () -1].size ()); F[0] = triangle[0][0]; for (int i = 1; i < triangle.size (), i++) for (int j = triangle[i].size () 1; J >= 0; j--) if (j = = 0) f[ J] = F[j] + triangle[i][j]; else if (j = = Triangle[i].size ()-1) f[j] = f[j-1] + triangle[i][j]; else f[j] = min (f[j-1], f[j]) + triangle[i][j]; int ret = Int_max; for (int i = 0; i < f.size (); i++) ret = min (ret, f[i]); return ret; }};
Leetcode | | 120, Triangle