Triangle
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 11 (i.e., 2 + < Span style= "color:red" >3 + 5 + 1 = one).
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.
Problem Solving Ideas:
Dynamic planning. Use D to record the shortest path from the root to the page, and I is the current number of rows. Then there are
D[J] = d[j-1] + triangle[i][j],j==i
D[J] = d[0] + triangle[i][0], j==0
D[j] = min (d[j-1], d[j]) + triangle[i][j], others.
Note that the last d[j-1] is used when calculating d[j], so you can press d[i. 0] In order to calculate.
Class Solution {public: int minimumtotal (vector<vector<int>>& triangle) { int n = Triangle.size (); if (n==0) { return 0; } if (n==1) { return triangle[0][0]; } int d[n]; D[0] = triangle[0][0]; for (int i=1, i<n; i++) {for (int j=i; j>=0; j--) { //here from high to low if (j==i) { d[j] = d[j-1] + triangle[ I][J]; } else if (j==0) { d[j] = d[0] + triangle[i][0]; } else{ D[j] = min (d[j-1], d[j]) + triangle[i][j];}} } int minpath = d[0]; for (int i=1; i<n; i++) { minpath = min (d[i], minpath); } return minpath;} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Triangle