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