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.
爬楼梯问题是斐波那契数的典型实现,由于递归会多次计算同一组斐波那契数,所以要采用dp,用空间复杂度换时间复杂度。
public class Solution {
public int climbStairs(int n) {
if(n<4)return n;
int []dp = new int[n+1];
for(int i=0;i<4;i++){
dp[i] = i;
}
for(int i=4;i<=n;i++){
dp[i] = dp[i-1]+dp[i-2];
}
return dp[n];
}
}