Leetcode Triangle-----java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.