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]
};