LeetCode 120. triangle path and the minimum (dynamic programming)

Title Description

Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes.
For example, a given triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).

Thinking

See link

Code

class Solution:
	def mininumTotal(self,triangle):
		if(not triangle):
			return 0
		n = len(triangle)
		if (n == 1):
			return triangle[0][0]
		for i in range(1,n):
			for j in range(len(triangle[i])):
				if(j==0):
					triangle[i][j] += triangle[i-1][j]
				elif(j == len(triangle[i]) - 1):
					triangle[i][j] += triangle[i-1][j-1]
				else:
					triangle[i][j] += min(triangle[i-1][j],triangle[i-1][j-1])
		return min(triangle[-1])
test = Solution()
test.mininumTotal([
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
])

effect

Here Insert Picture Description

Published 80 original articles · won praise 239 · Views 7102

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/104078744
Recommended