[Leetcode] [JavaScript] Triangle

Source: Internet
Author: User

Triangle

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.

https://leetcode.com/problems/triangle/

Dynamic planning, find a law.

Each layer infers the current minimum and is based on the minimum and maximum of the previous layer.

The min of the first point can only be the result of the upper layer plus oneself; the last point's Min can only be the upper level result plus oneself; the middle point is 2 choices, the upper level corresponds to the point of the subscript and (corresponding to the subscript-1).

1 /**2 * @param {number[][]} triangle3 * @return {number}4  */5 varMinimumtotal =function(triangle) {6     varPassed = triangle[0];7     if(Triangle.length = = 1){8         returnPassed[0];9     }Ten     varMin =Infinity; One      for(vari = 1; i < triangle.length; i++){ A         varrow =Triangle[i]; -         varCurrrow = []; -          for(varj = 0; J < Row.length; J + +){ the             varTMP =NULL; -             if(j = = 0){ -TMP = row[0] + passed[0]; -}Else if(j = = Row.length-1){ +TMP = Row[j] + passed[j-1]; -}Else{ +TMP = Math.min (Row[j] + passed[j], Row[j] + passed[j-1]); A             } at Currrow.push (TMP); -             if(i = = Triangle.length-1){ -                 if(TMP <min) { -Min =tmp; -                 } -             } in         } -Passed =Currrow; to     } +     returnmin; -};

[Leetcode] [JavaScript] Triangle

Related Article

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.