Skip to content

Commit 9f9ef6a

Browse files
committed
[20180416] medium problems
1 parent 377dea5 commit 9f9ef6a

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

β€ŽREADME.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
| [0103](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/) | Binary Tree Zigzag Level Order Traversal | medium | python | |
3737
| [0107](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/) | Binary Tree Level Order Traversal II | easy | python | |
3838
| [0111](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | Minimum Depth of Binary Tree | easy | [python](πŸ™‚easy/0111.Minimum-Depth-of-Binary-Tree/minimum_depth_of_binary_tree.py) | tree |
39+
| [0120](https://leetcode.com/problems/triangle/) | Triangle | medium | [python](πŸ€”medium/0120.Triangle/triangle.py) | |
3940
| [0121](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | Best Time to Buy and Sell Stock | easy | [python](πŸ™‚easy/0121.Best-Time-to-Buy-and-Sell-Stock/best_time_to_buy_and_sell_stock.py) | |
4041
| [0122](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description) | Best Time to Buy and Sell Stock II | easy | python | |
4142
| [0139](https://leetcode.com/problems/word-break/description/) | Word Break | medium | python | |
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# 120. Triangle
2+
# https://leetcode.com/problems/triangle/
3+
4+
from typing import List
5+
6+
7+
class Solution(object):
8+
# triangle μ—μ„œ minimum path λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œλ‹€.
9+
# μ „ν˜•μ μΈ dp λ¬Έμ œλ‹€.
10+
def minimumTotal(self, triangle: List[List[int]]) -> int:
11+
"""
12+
:type triangle: List[List[int]]
13+
:rtype: int
14+
"""
15+
16+
height = len(triangle)
17+
18+
if height == 1:
19+
return min(triangle[0])
20+
21+
# ν˜„μž¬ κ°’μ˜ μ΅œμ†Œ 값은 λ°”λ‘œ μœ„μ˜ (height-1) κ°’ κ³Ό λ°”λ‘œ μœ„μ˜ μ˜†μ— κ°’ 의 μ΅œμ†Œ κ°’ + ν˜„μž¬ 값이닀.
22+
# κ°€μž₯ λ„νŠΈλ¨Έλ¦¬μ— μžˆλŠ” κ²ƒλ“€λ§Œ μ˜ˆμ™Έ 처리λ₯Ό ν•΄μ£ΌλŠ” 방식(λ„νŠΈλ¨Έλ¦¬μ˜ 것듀은 λ°”λ‘œ μœ„μ˜ κ²ƒλ§Œ 영ν–₯을 λ°›λŠ”λ‹€) 으둜 top-down 으둜 κ΅¬ν–ˆλ‹€.
23+
for i in range(1, height):
24+
for j in range(len(triangle[i])):
25+
if j == 0:
26+
triangle[i][j] = triangle[i - 1][j] + triangle[i][j]
27+
continue
28+
if j == len(triangle[i]) - 1:
29+
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i][j]
30+
continue
31+
triangle[i][j] = min(triangle[i - 1][j - 1], triangle[i - 1][j]) + triangle[i][j]
32+
33+
return min(triangle[height - 1])
34+
35+
36+
if __name__ == '__main__':
37+
sol = Solution()
38+
assert sol.minimumTotal([
39+
[2],
40+
[3, 4],
41+
[6, 5, 7],
42+
[4, 1, 8, 3]
43+
]) == 11

0 commit comments

Comments
Β (0)