題目連結(https://leetcode.com/problems/climbing-stairs/description)
You are climbing a staircase. It takes n
steps to reach the top.
Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
DP 與數學結合的有趣題目
1 <= n <= 45
dp(4)
時,會重複計算 dp(3)
和 dp(2)
,這會使得算法的時間複雜度呈指數級增長,變得非常低效。dp[i]
表示走到第 i 層的方式數dp[n]
**#一維 DP**
class Solution{
public:
int climbstairs(int n){
if(n == 1) return 1;
vector<int> dp(n+1);
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i <= n; i++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
**#一維 DP(空間優化版)**
class Solution {
public:
int climbStairs(int n) {
if(n == 1) return 1;
int dp1 = 1;
int dp2 = 2;
for(int i = 3 ; i <= n; i++){
int temp = dp2;
dp2 = dp1 + dp2;
dp1 = temp;
}
return dp2;
}
};
這題 test 不太用多解釋
n = 1 → 1 種走法
n = 2 → 2 種走法 (1+1, 2)
n = 3 → 3 種走法 (1+1+1, 1+2, 2+1)
n = 5 → 8 種走法
746. Min Cost Climbing Stairs
迴圈索引
for(int i = 3; i <= n; i++)
不要寫成 i < n
或 dp[n] = ...
,會造成錯誤。
空間優化
dp
陣列,用兩個變數即可。邊界條件
n = 1
, n = 2
時需要特別處理。ps. 部分內容經 AI 協助整理