0
点赞
收藏
分享

微信扫一扫

每天一道算法题(28)

你在爬楼梯,需要n步才能爬到楼梯顶部

每次你只能向上爬1步或者2步。有多少种方法可以爬到楼梯顶部?

public int climbStairs (int n) {
if(n==1 || n==0){
return 1;
}
/*
n=2,需要2步上楼梯,我们有2种方法
n=3,需要3步上楼梯,有3种方法
n=4,需要4步上楼梯,有5种
则n步楼梯,有f(n-1)+f(n-2)种方法
*/
int[] step = new int[n+1];
step[1] = 1;
step[2] = 2;
for(int i = 3;i<=n;i++){
step[i] = step[i-1]+step[i-2];
}
return step[n];
}
举报

相关推荐

0 条评论