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.
每次爬1到2步有多少种方法可以爬上n阶台阶
思路:
n=1时 有1种方法
n=2时,有两种方法
n=3时,有先爬到台阶2再爬1步(此处有f(2)种方法,最后一步唯一且确定),与先爬到台阶1再爬2步(此处有f(1)种方法,最后一步唯一且确定)两种策略,共f(2)+f(1)
n=4时,有先爬到台阶3再爬1步,与先爬到台阶2再爬2步两种策略,共f(3)+f(2)
n=5时,.....
即有f(n)=f(n-1)+f(n-2)
var climbStairs = function(n) {
var res = []
res[1] = 1
res[2] = 2
for(var i =3; i<n; i++){
res[i] = res [i-1] + res [i-2]
}
return res[n]
};