Leetcode "Triangle" Python implementation

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

code : OJ Test via runtime:82 ms

1 classSolution:2     #@param triangle, a list of lists of integers3     #@return An integer4     defminimumtotal (self, triangle):5         #Special Case6         ifLen (triangle) = =0:7             return08         #DP Visit9Level =len (triangle)TenDP = [0 forIinchrange (level)] One          forIinchRange (level): A              forJinchRange (len (triangle[i]) -1,-1,-1): -                 ifJ==len (Triangle[i])-1 : -DP[J] = dp[j-1] +Triangle[i][j] the                 elifj==0: -Dp[0] = dp[0] +Triangle[i][0] -                 Else: -Dp[j] = min (dp[j-1],dp[j]) +Triangle[i][j] +         returnMIN (DP)

Ideas :

Typical dynamic programming, like the unique path, see details

Http://www.cnblogs.com/xbf9xbf/p/4250359.html

In addition, this problem has a bonus, how to use as little as possible extra space.

The general DP idea is to define an O (n) space, with additional space such as a triangle size.

This is only used for the size of the bottom layer of the triangle.

When traversing the layer I, the space storage of Dp[1:len (Triangle[i]) is used to store the minimum and the nodes to the first level of each node.

Note here: You can save the array space by traversing backwards. This is a common operation technique for array, see details

Http://www.cnblogs.com/xbf9xbf/p/4240257.html

Continuous brush problem, can be more related to the skills of the front and back, the ability to improve the code has a certain help.

Leetcode "Triangle" Python implementation

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.