Leetcode's "Dynamic Planning": Triangle

Source: Internet
Author: User

Topic links

Title Requirements:

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

 1  [  [2  ],  3  [3 , 4  ],  4  [6 , 5 , 7  ],  5  [1 , 8 , 3   6 ] 

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.

The specific code is as follows:

1 classSolution {2  Public:3     intMinimumtotal (vector<vector<int> > &triangle) {4         introws =triangle.size ();5         if(Rows = =0)6             return 0;7         8         int* DP =New int[rows];9         intSzoflastrow = Triangle[rows-1].size ();Ten          for(inti =0; i < Szoflastrow; i++) OneDp[i] = triangle[rows-1][i]; A          -          for(inti = Rows-2; I >-1; i--) -         { the             intcols =triangle[i].size (); -              for(intj =0; J < cols; J + +) -DP[J] = triangle[i][j] + min (dp[j], dp[j +1]); -         } +          -         returndp[0]; +     } A};
View Code

The most central areas of this program are:

1]);

The diagram can be expressed as follows:

  

An example of this is:

  

It is important to note that the only change in this example is dp[0],dp[1] and it has not changed.

Leetcode's "Dynamic Planning": 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.