[C + +] leetcode:81 Triangle

Source: Internet
Author: User

Title:

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 11   (i.e., 2  + < Span style= "color:red" >3  + 5  +  1  = one).

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.

Wrong idea:

depending on the test instructions, each time you choose to consider only adjacent numbers, you maintain a positional variable and a sum variable directly. forget to consider that the triangle may have duplicate numbers (the selection is minimal, does not necessarily lead to global minimum), the greedy algorithm does not apply here. Need to use dynamic planning.

Error Code:

<span style= "FONT-SIZE:14PX;" >class Solution {public:    int minimumtotal (vector<vector<int> > &triangle) {        if ( Triangle.size () = = 0 | | Triangle[0].size () = = 0) return 0;        int sum = triangle[0][0];        int position = 0;                for (int i = 1; i < triangle.size (); i++)        {            if (Triangle[i][position] < triangle[i][position+1])            {                Sum + = Triangle[i][position];            }            else            {                sum + = triangle[i][position+1];                Position + = 1;            }        }                return sum;    }}; </span>

submission Result:wrong Answer moreDetails
Input: [[ -1],[2,3],[1,-1,-3]]
Output: 0
Expected: -1



greedy path: -1-->2-->-1; correct path: -1-->3-->-3


Correct solution: Dynamic programming

idea: due to the dynamic planning of the Top-down, there is redundancy in the space, each time need to repeat the results (such as the first behavior convenient second row calculation, need to save two values), and the need for special processing of the tail-end elements. So consider using bottom-up dynamic programming, starting from the last layer to calculate, set Dp[i][j] for the first layer J elements as the starting point of the smallest path and dynamic programming equation is:

DP[I][J] = value[i][j] + min (dp[i-1][j], dp[i-1][j+1]) (according to the example in the topic, the next element in test instructions (i) and the right-side element (i+1), excluding the element on the left (i-1))

Bottom-up calculations, each DP value holds the actual minimum path of the node and.

Because the sum of each layer is related to the value of its next layer, we only need a one-dimensional array to hold the underlying values

for thekth 

Level:Minpath[I] = min(Minpath[I],Minpath[I+1]) + Triangle[k][I];

note here, since we are min (Minpath[i], minpath[i+1]), unlike the dynamic plan previously handled, [C + +] leetcode:56 Unique Paths. Here two values minpath[i", minpath[i+1] are not updated, that is, dp[i-1][j", dp[i-1][j+1], is the value of the next layer.

Attention:

1. When initializing, we use the value of the last line.

Bottom-up initializes the DP        vector<int> DP (Triangle.back ()) with the last line of elements;
2. Loop, we start from the penultimate line, and the value of each row of columns can only be taken to the value of the row coordinates (maximum), for example, the last column of the penultimate row coordinates n-2. Note the loop condition.

for (int i = row-2; I >= 0; i--)        {for            (int j = 0; J <= I; j + +)            {                dp[j] = triangle[i][j] + min (dp[j], Dp[j+1]);            }        }
3. Finally returns the value of Dp[0], which is the last shortest path to top.

Complexity: Time complexity O (n^2), Space O (N)

AC Code:

Class Solution {public:    int minimumtotal (vector<vector<int> > &triangle) {        int row = Triangle.size ();        if (row = = 0 | | triangle[0].size () = = 0) return 0;                Bottom-up initializes the DP        vector<int> DP (Triangle.back ()) with the last line of elements;                for (int i = row-2; I >= 0; i--)        {for            (int j = 0; J <= I; j + +)            {                dp[j] = triangle[i][j] + min (dp[j], Dp[j+1]);            }        }                return dp[0];}    ;





[C + +] leetcode:81 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.