Description
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
Explain
這道題是關(guān)于動態(tài)規(guī)劃的痛倚。很經(jīng)典翎碑。這道題如果用遞歸做洲守,會出現(xiàn)太慢的情況属铁。雖然遞歸的思想我個人覺得是很正確的臊旭。那沒辦法,只能用動態(tài)規(guī)劃做。每次只能走一階或兩階。那么我們想想绸硕,如果要到第三階,這個時候就相當(dāng)于已經(jīng)走了一階魂毁,現(xiàn)在選擇兩階和已經(jīng)走了兩階玻佩,現(xiàn)在選擇走一階。那么 DP[n] = DP[n-1] + DP[n-2] 動態(tài)規(guī)劃的狀態(tài)方程是不是就出來了席楚。那么下面上代碼
Code
class Solution {
public:
int climbStairs(int n) {
int a, b, c, temp;
a = 1;
b = 2;
if (n == 1) return 1;
for (int i = 3; i <= n; i++) {
temp = b;
b = b + a;
a = temp;
}
return b;
}
};