LeetCode 0070. Climbing Stairs爬樓梯【Easy】【Python】【動態規劃】
Problem
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
問題
假設你正在爬樓梯。需要 n 階你才能到達樓頂。
每次你可以爬 1 或 2 個臺階。你有多少種不同的方法可以爬到樓頂呢?
注意: 給定 n 是一個正整數。
示例 1:
輸入: 2
輸出: 2
解釋: 有兩種方法可以爬到樓頂。
1. 1 階 + 1 階
2. 2 階
示例 2:
輸入: 3
輸出: 3
解釋: 有三種方法可以爬到樓頂。
1. 1 階 + 1 階 + 1 階
2. 1 階 + 2 階
3. 2 階 + 1 階
思路
動態規劃
初始條件和斐波那契數列有點區別:dp_0 = 1,dp_1 = 1。
遞推公式:fib(n) = fib(n - 1) + fib(n - 2)
時間複雜度: O(n)
空間複雜度: O(1)
Python3代碼
class Solution:
def climbStairs(self, n: int) -> int:
# 初始條件和斐波那契數列有區別
dp_0, dp_1 = 1, 1
for _ in range(n):
dp_0, dp_1 = dp_1, dp_0 + dp_1
return dp_0