바위타는 두루미
[leetcode]120. Triangle 본문
728x90
120. 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).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
class Solution(object):
def minimumTotal(self, triangle):
curMinList = triangle[-1]
for level in range(len(triangle)-2,-1,-1):
nextList = curMinList
curMinList = []
curList = triangle[level]
for i , num in enumerate(curList):
curMinList.append( min(num+nextList[i],num+nextList[i+1]))
return curMinList[0]
더 깔끔한 코드
class Solution(object):
def minimumTotal(self, triangle):
for i in range(len(triangle)-1,0, -1):
for j in range(i):
triangle[i-1][j] += min(triangle[i][j] ,triangle[i][j+1])
return triangle[0][0]
'Study > Algorithm' 카테고리의 다른 글
[leetcode]31. Next Permutation (0) | 2019.08.15 |
---|---|
[leetcode]29. Divide Two Integers (0) | 2019.08.15 |
16.11 다이빙 보드 (0) | 2019.08.14 |
16.10 살아있는 사람 (0) | 2019.08.14 |
16.1 숫자 교환 (0) | 2019.08.14 |
Comments