본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 746. Min Cost Climbing Stairs(최소 비용 계단 오르기)

by 뒬탕 2024. 9. 17.
반응형

LeetCode 문제 해석 및 풀이 방법

문제 746. Min Cost Climbing Stairs(최소 비용 계단 오르기)

난이도 : 쉬움🟢 바로가기

 

문제 설명

영문

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

 

You can either start from the step with index 0, or the step with index 1.

 

Return the minimum cost to reach the top of the floor.

 

한글

 cost[i]가 계단의 i th 단계에서 사용해야되는 비용을 나타내는 정수 배열 cost가 주어집니다. 비용을 지불하면 한 단계 또는 두 단계의 계단을 올라갈 수 있습니다.

 

시작은 인덱스 0 또는 1부터 가능합니다.

 

꼭대기 층에 도달하는 데 필요한 최소 비용을 반환합니다.

 

제한조건

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999

 

입출력 예

입력 출력
cost = [10,15,20] 15
cost = [1,100,1,1,1,100,1,1,100,1] 6

 

해답 및 해설

파이썬 (Python)

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        n = len(cost)
        dp = [None] * (n+1)
        dp[0], dp[1] = 0, 0

        for i in range(2, n+1):
            dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])

        return dp[-1]

배열을 새로 만들고, 해당 층까지 올라가는데 드는 최소 비용을 저장해둔다. 이런 방식으로 꼭대기 층까지 구해준다.

 

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        cost.append(0);

        for i in range(len(cost) -3,-1,-1):
            cost[i] = cost[i] + min(cost[i+1], cost[i+2])

        return min(cost[0], cost[1])

 역발상으로 원래 배열에 현재 층부터 꼭대기 층까지 가는데 걸리는 최소 비용을 저장해두는 풀이도 있었다. 이렇게 모든 층을 구한 다음 맨 처음 시작할 때 0층 또는 1층 중 비용이 적게 드는 쪽을 고른다.

반응형

댓글