1. 程式人生 > >[leetcode 70]Climbing Stairs

[leetcode 70]Climbing Stairs

col 超時 gin pub bing n-2 consola href rgb

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?

爬臺階,你每次能夠上一層或者兩層,問上n層你共同擁有多少何種方法

f(n)=f(n-1)+f(n-2)

動規,記得保存n-1和n-2的結果,直接使用遞歸會超時

AC代碼

class Solution {
public:
int climbStairs(int n) {
int count[n+1];
count[0]=0;
count[1]=1;
count[2]=2;
if(n==1)
return 1;
if(n==2)
return 2;
for(int i=3;i<=n;++i)
count[i]=count[i-1]+count[i-2];
return count[n];
}
};



其它Leetcode題目AC代碼:https://github.com/PoughER/leetcode

[leetcode 70]Climbing Stairs