[Leedcode 120] Triangle

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 you be able to does this using only O(n) extra space, where n is the total Number of rows in the triangle.

 Public classSolution { Public intMinimumtotal (list<list<integer>>triangle) {        //space complexity is O (n), n is the number of triangles, time complexity is O (k), K is the number of the whole triangle//from the bottom up, dynamic programming, the test instructions is only adjacent, so the state transfer equation can be calculated        intn=triangle.size (); intdp[]=New int[n];  for(inti=n-1;i>=0;i--){             for(intj=0;j<=i;j++){                if(i==n-1) {Dp[j]=Triangle.get (i). get (j); }Else{Dp[j]=math.min (dp[j],dp[j+1]) +Triangle.get (i). get (j); }            }        }        returnDp[0]; }}

[Leedcode 120] Triangle

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.