Leetcode Note: Triangle

Source: Internet
Author: User

Leetcode Note: Triangle

I. Description

Given a triangle, find the minimum path sum from top to bottom. Each step you may 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 is 11 (I. e., 2 + 3 + 5 + 1 = 11 ).

Note: Bonus point if you are able to do this using only O (n) extra space, where n is the total number of rows in the triangle.

Ii. Question Analysis

Use Dynamic Planning. Set From topiThekThe minimum path length of each vertex is expressedf(i, k), Thenf(i, k) = min{f(i-1,k), f(i-1,k-1)} + d(i, k), Whered(i, k)Indicates the element of column k of row I in the original triangle array. Then we can obtain from the first row to the finallength-1RowkMinimum path length of each element, and then comparelength-1The path length of all elements in the row, and the minimum value is obtained.

Note the boundary condition that the first and last elements in each row have only one neighbor in the previous row. Other intermediate elements have two adjacent elements in the previous line.

Iii. Sample Code

class Solution {public:    int minimumTotal(vector
  
    > &triangle) {            vector< vector
   
     >::size_type length = triangle.size();            if(length == 0){                return 0;            }            int i, j;            for(i=1;i
    
     ::size_type length_inner = triangle[i].size();                for(j=0;j
     
    
   
  

 

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.