Algorithm/νλ‘κ·Έλλ¨Έμ€
[νλ‘κ·Έλλ¨Έμ€ / Python] μ μ μΌκ°ν
meeeeejin
2021. 4. 6. 16:22
λ¬Έμ λ§ν¬: programmers.co.kr/learn/courses/30/lessons/43105
λ¬Έμ μ€λͺ
κ±°μ³μ¨ μ«μλ€μ ν©μ μ΅λκ°μ μ μ₯νλ dp ν μ΄λΈμ μμ±ν©λλ€.
triangle[i][j]μ λλ¬νλ λ°©λ²μ λ κ°μ§ λ°©λ²μ΄ μμ΅λλ€.
- triangle[i - 1][j - 1]μμ triangle[i][j]λ‘ κ°κΈ°
- triangle[i - 1][j]μμ triangle[i][j]λ‘ κ°κΈ°
dp[i][j]λ μ λ κ°μ§ κ° μ€μμ μ΅λκ°μ μ μ₯ν©λλ€.
μλ₯Ό λ€μ΄ triangle λ°°μ΄μ΄ λ€μκ³Ό κ°λ€λ©΄
7 | ||||
3 | 8 | |||
8 | 1 | 0 | ||
2 | 7 | 4 | 4 | |
4 | 5 | 2 | 6 | 5 |
dp ν μ΄λΈμ λ€μκ³Ό κ°μ΄ κ³μ°λ©λλ€.
7 | ||||
10(7 + 3) | 15(7 + 8) | |||
18(10 + 8) | 16(15 + 1) | 15(15 + 0) | ||
20(18 + 2) | 25(18 + 7) | 20(16 + 4) | 19(15 + 4) | |
24(20 + 4) | 30(25 + 5) | 27(25 + 2) | 26(20 + 6) | 24(19 + 5) |
dp ν μ΄λΈ κ³μ°μ΄ λλ νμ λ§μ§λ§ μ€μ μμ μ€μμ μ΅λκ°μ λ°νν©λλ€.
μμ€μ½λ
def solution(triangle):
# dp ν
μ΄λΈ μ΄κΈ°ν
dp = [[0] * len(triangle) for _ in range(len(triangle))]
dp[0][0] = triangle[0][0]
# κ±°μ³κ° μ«μμ μ΅λκ° κ΅¬νκΈ°
for i in range(0, len(triangle) - 1):
for j in range(len(triangle[i])):
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + triangle[i + 1][j])
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + triangle[i + 1][j + 1])
return max(dp[-1]) # dp ν
μ΄λΈμ λ§μ§λ§ μμλ€ μ€ μ΅λκ° λ°ν
728x90