leetcode120--Triangle

# 小郑之家~

### 题目


Given a triangle, find the minimum path sum from top to bottom. Each step you may 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 + 3 + 5 + 1 = 11).



### 解决办法1

python代码如下

class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if len(triangle)==0:
return 0

# 申请和这个一样大的来存结果
a = []
for i in range(len(triangle)):
a.append([0 for i in range(i+1)])
if i==0:
a[0][0] = triangle[0][0]
else:
for j in range(len(a[i])):
# cal a[i][j]
if j==0:
a[i][0]=a[i-1][0]+triangle[i][0]
elif j == (len(a[i])-1):
a[i][-1] = a[i-1][-1] + triangle[i][-1]
else:
a[i][j] = triangle[i][j] + min(a[i-1][j-1], a[i-1][j])

return min(a[-1])


• 还可以不申请新的空间，而直接在triangle上更改值

class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if not triangle:
return None
i = len(triangle)
for row in range(1, i):
triangle[row][0] += triangle[row - 1][0]
triangle[row][-1] += triangle[row - 1][-1]
for row in range(2, i):
j = len(triangle[row])
for column in range(1, j - 1):
triangle[row][column] += min(triangle[row - 1][column - 1], triangle[row - 1][column])
return min(triangle[-1])



class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""

for i in range(len(triangle)-2,-1,-1):
for j in range(0,i+1):
triangle[len(triangle)-1][j] = triangle[i][j] + min(triangle[len(triangle)-1][j],triangle[len(triangle)-1][j+1])

return triangle[len(triangle)-1][0]