题目描述
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.
题目本质:
因为一次只能迈一步或者两步,所以当在第n步时,可以是从n-1步迈一步,也可以是从n-2步迈了两步,所以到达第n步的方法数目就是到n-1步和到n-2步的方法数目之和。类似于斐波那契数列,F(n) = F(n-1)+F(n-2)。
迭代实现复杂度太高,可以线性复杂度解决此问题,需要不断更新Fn-1,Fn-2
public class Solution {
public int climbStairs(int n) {
int fn1 = 1, fn2 = 2;
int fn = 0;
for(int i = 2; i < n; i++){
fn = fn1 + fn2;
fn2 = fn1;
fn1 = fn;
}
return fn;
}
}