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.
Find the smallest path.
Use recursion for the first time, timed out.
Public classSolution { Public intMinimumtotal (list<list<integer>> triangle) {intLen =triangle.size (); intresult = Triangle.get (0). Get (0); Result= GetResult (result,0,0, triangle); returnresult; } Public Static intGetResult (intResultintPosintNum,list<list<integer>>triangle) { if(num = = Triangle.size ()-1 ) returnresult; intNUM1 = Triangle.get (num+1). Get (POS); intAns =result; Ans+=NUM1; Ans= GetResult (ans,pos,num+1, triangle); NUM1= Triangle.get (num+1). Get (pos+1); Result+=NUM1; Result= GetResult (result,pos+1,num+1, triangle); returnAns>result?Result:ans; }}
So you still need to use DP. More simple DP applications.
Public classSolution { Public intMinimumtotal (list<list<integer>>triangle) { intHeight =triangle.size (); int[] DP =New int[height]; dp[0] = dp[0]+triangle.get (0). Get (0); for(inti = 1;i){ intA = Dp[0],b = Dp[1]; dp[0] = Dp[0]+triangle.get (i). Get (0); for(intj = 1;j<i;j++) {Dp[j]= Math.min (A, B) +Triangle.get (i). get (j); A=b; b= Dp[j+1]; } Dp[i]= A +Triangle.get (i). get (i); } intresult = Dp[0]; for(inti = 1;i) Result=math.min (Result,dp[i]); returnresult; }}
Leetcode Triangle-----java