๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [DP] [Python] Level3_์ •์ˆ˜ ์‚ผ๊ฐํ˜•

Dbswnstjd 2023. 2. 11. 17:18

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/43105

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 3๋‹จ๊ณ„ - ์ •์ˆ˜ ์‚ผ๊ฐํ˜•
def solution(triangle):
    answer = 0
    dp = [[0]*i for i in range(1, len(triangle)+1)] 
    dp[0][0] = triangle[0][0] 
    dp[1][0] = dp[0][0] + triangle[1][0]
    dp[1][1] = dp[0][0] + triangle[1][1]

    for i in range(2, len(triangle)):
        for j in range(len(triangle[i])):
            if j == 0:
                dp[i][j] = dp[i-1][j] + triangle[i][j]
            elif i == j:
                dp[i][j] = dp[i-1][j-1] + triangle[i][j]
            else:
                dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]
    answer = max(dp[-1])
    return answer
print(solution([[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]))

DP๋ฅผ ์ด์šฉํ•œ ํ’€์ด

ํ•ญ์ƒ ์ธ๋ฑ์Šค ์ชฝ์—์„œ ๋ฌธ์ œ๋ฅผ ์ผ์œผ์ผœ์„œ ์‹œ๊ฐ„์„ ๋‚ญ๋น„ํ•˜๊ฒŒ๋œ๋‹ค..

์ž˜ ํ™•์ธํ•˜๋„๋ก ํ•˜์ž