leetcode 746. Min Cost Climbing Stairs

wonderful world·2021년 10월 4일
0

leetcode

목록 보기
3/21

https://leetcode.com/problems/min-cost-climbing-stairs/

Description

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.

Example 1

Input: cost = [10,15,20]
Output: 15
Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.

Solution

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        # bottom-up, dynamic programming
        dp = [[0,0] for i in range(len(cost)+1)]
        def f(cost):
            count = len(cost)
            dp[0] = [cost[0], cost[0]]
            dp[1] = [cost[0] + cost[1], cost[1]]
            for i, c in enumerate(cost):
                if i < 2: continue
                    
                # step-one
                step_one = min(dp[i-1]) + c
                # step-two
                step_two = min(dp[i-2]) + c
                
                dp[i][0] = step_one
                dp[i][1] = step_two
            
            dp[count][0] = min(dp[count-1])
            dp[count][1] = min(dp[count-2])
            
            return min(dp[count])
        return f(cost)
    
    def minCostClimbingStairs0(self, cost: List[int]) -> int:
        # top-down, recursive version
        def f(cost):
            if len(cost) < 2: return 0
            step_one = cost[0] + f(cost[1:])
            step_two = cost[1] + f(cost[2:])
            return min(step_one, step_two)
        
        return f(cost)
profile
hello wirld

0개의 댓글