"Leetcode" Triangle (#120)

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 is one (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.

Analytical:

The purpose of this subject is to give a triangular matrix, and the minimum path is obtained. Only one integer can be selected per layer, and the integers on the previous and next levels must be contiguous.

Ideas:

    1. Dynamic planning: The minimum path length to the K-vertex of layer I is expressed as f (i,j), then:

F (i,j) = min{f (i,j + 1), f (i + 1, j + 1)}+ (I,J)

    1. The main concern is that space complexity should not exceed N.
    2. Note the boundary conditions-the first and last elements in each row have only one neighbor in the previous line. The other intermediate elements have two adjacent elements in the previous row.

Algorithm implementation code:

Class Solution {Public:int minimumtotal (vector<vector<int> > &triangle) {    int len = triangle.size () for (int i = len-2; I >= 0, i--) for (int j = 0; J < i + 1; ++j) {if (Triangle[i+1][j] > Triangle[i+1][j+1]) {Trian GLE[I][J] + = triangle[i+1][j+1];} ELSE{TRIANGLE[I][J] + = Triangle[i+1][j];}} return triangle[0][0];};

  

"Leetcode" Triangle (#120)

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.