Programming Camp – Algorithm Training Camp – Day 38

1. Fibonacci Number (Leetcode Number: 509)

class Solution(object):
    def fib(self, n):
        """
        :type n: int
        :rtype: int
        """
        res, pre_2, pre_1 = 0, 0, 1
        
        if n == 0 or n == 1:
            return n
        
        for i in range(2, n + 1):
            res = pre_1 + pre_2
            pre_2 = pre_1
            pre_1 = res
        return res

2. Climbing Stairs (Leetcode Number: 70)

The possible ways of climbing to the target top n is the sum of the solutions of its previous stair and the one before the previous start.

class Solution:
    def climbStairs(self, n: int) -> int:
        if n < 3:
            return n
        dp =[0] * 2
        res = 0
        dp[0] = 1
        dp[1] = 2
        
        for i in range(3, n + 1):
            res = dp[0] + dp[1]
            dp[0] = dp[1]
            dp[1] = res
        return res

3. Min Cost Climbing Stairs (Leetcode Number: 746)

As the algorithm allows climbing either1 or 2 steps, so every staircase could be reached either from the staircase before itself or 2 steps before itself -> Record the mimum steps taken to reach each staircase and compare the value of dp[i - 2] and dp[i - 1], which are the last two staircases. 

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        dp = [0] * len(cost)
        dp[0] = cost[0]
        dp[1] = cost[1]
        
        for i in range (2, len(cost)):
            dp[i] = min(dp[i - 2] + cost[i], dp[i - 1] + cost[i])
            
        min_res = min(dp[len(cost) - 2], dp[len(cost) - 1])
            
        return min_res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值