"Leetcode" triangle to find the minimum and path

Source: Internet
Author: User

Today no matter, do three leetcode water problem, anger more two blog, also quite good. The two updates today are simple questions for DP solutions.

    • The subject requirements are as follows.
Given a triangle, find theMinimum path sum fromTop toBottom. Each step, may move toAdjacent numbers on  theRowbelow. For example,given  theFollowing triangle[[2],    [3,4],   [6,5,7],  [4,1,8,3]]the Minimum path sum fromTop toBottom is  One(i.e.,2+3+5+1= One). Note:bonus PointifYou are able toDo the using only O (n) extraSpace,whereN is  theTotal Number  ofRowsinch  theTriangle.
  • The title says it's better to have an O (n) space complexity, and to think that general motion rules may require O ( n 2 ) of the space, how can only use O (n), a little bit of brain turn to think that there is no need to save the path from the root to each node and Ah! We calculate to the first line only need to save the current line of the shortest path of each node, and before we do not care at all, so apply an array of n, each can overwrite the previous. But notice a small place, to update the path of each row, start from the right, or the shortest of the previous line will be overwritten.
    • AC Code
classSolution { Public:intMinimumtotal ( vector<vector<int>>& Triangle) {intn = triangle.size ();if(n==0)return 0;if(n==1)returntriangle[0][0];intdp[n+1];intMin = Int_max; for(intI=0; i<n+1; i++) Dp[i]=int_max; dp[1] = triangle[0][0]; for(intI=1; i<n;i++) { for(intj=i+1;j>0; j--) {Dp[j]=min (dp[j-1],DP[J]) +triangle[i][j-1];if(i==n-1&&dp[j]<min) {Min = Dp[j]; }            }        }returnMin; }};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode" triangle to find the minimum and path

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.