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 you be able to does this using only O(n) extra space, where n is the total Number of rows in the triangle.
Starting with a top-down approach to finding the minimum value, the boundary handling is a bit cumbersome and tuned several times.
1 Public classSolution {2 Public intMinimumtotal (list<list<integer>>triangle) {3 intLen =triangle.size ();4 int[] DP =New int[Len+1];5 Arrays.fill (dp,integer.max_value);6DP[1] = triangle.get (0). Get (0);7 8 for(inti = 1; I <len; i++){9 for(intj = Triangle.get (i). Size (); J > 0; j--){TenDP[J] = Triangle.get (i). Get (J-1) + math.min (dp[j],dp[j-1]); One } A } - intMin =Integer.max_value; - for(inti = 1;i <= triangle.size (); i++){ theMin =math.min (Min,dp[i]); - } - returnmin; - } +}
Solution two uses bottom-up:
1 Public classSolution {2 Public intMinimumtotal (list<list<integer>>triangle) {3 intLen =triangle.size ();4 int[] DP =New int[Len];5 for(inti = 0; i< Len; i++){6Dp[i] = Triangle.get (len-1). get (i);7 }8 for(inti = len-2; i>=0; i--){9 for(intj = 0; J < Triangle.get (i). Size (); J + +){TenDP[J] = Triangle.get (i). Get (j) + Math.min (dp[j],dp[j+1]); One } A } - returnDp[0]; - } the}
Triangle Java Solutions