Leetcode------Triangle

Source: Internet
Author: User

Title: Triangle
Pass Rate: 27.1%
Difficulty: Medium

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.

Dynamic programming topics, bottom-up, minimum and must be the minimum of each row, then from below to start merging upward, the formula is res[i][j]=res[i+1][j]+res[i+1][j+1]

The formula explanation starts with the last line, each time the smaller values of J and J+1 are selected plus the J assignment of the previous line to J, and so on

1  Public classSolution {2      Public intMinimumtotal (list<list<integer>>triangle) {3         if(Triangle.size () ==1)returnTriangle.get (0). Get (0);4         int[] res=New int[Triangle.size ()];5          for(intI=0;i<triangle.size (); i++){6Res[i]=triangle.get (Triangle.size ()-1). get (i);7         }8          for(intI=triangle.size () -2;i>=0;i--){9              for(intJ=0;j<triangle.get (i). Size (); j + +){TenRes[j]=math.min (res[j],res[j+1]) +Triangle.get (i). get (j); One             } A         } -         returnRes[0]; -     } the}

Leetcode------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.