好久沒有刷題了,感覺手都生了。今天來道簡單點的題目——爬樓梯;
題目如下:
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?
Subscribe to see which companies asked this question
看到題目我們第一反應就是利用遞歸的思想,是以我的第一個版本的代碼如下:
class Solution {
public:
int climbStairs(int n) {
if (n == 0)return 0;
else if (n == 1)return 1;
else if (n == 2)return 2;
else return climbStairs(n-1) + climbStairs(n-2);
}
};
這種情況下當n=4的時候運作逾時,很明顯,我們可以用空間來換時間。每當我們得到一個n的結果的時候就将它儲存到容器re中,當下次需要用到某個n的時
候可以直接從容器中取,而無需再利用遞歸再求一次值。遞歸求解方程式climbStairs(n)=climbStairs(n-1) + climbStairs(n-2);其實也是動态規劃的思想;改進
之後的代碼如下:
class Solution {
public:
int climbStairs(int n) {
vector<int>re(n+1,0);
if (n == 0)return 0;
else if (n == 1)return 1;
else if (n == 2)return 2;
else {
re[1] = 1;
re[2] = 2;
for (int i = 3; i <= n; i++){
re[i] = re[i - 1] + re[i - 2];
}
return re[n];
}
}
};
運作結果:
Submission Result: Accepted More Details
Next challenges: (H) Wildcard Matching (H) Palindrome Partitioning II (M) Android Unlock Patterns