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?
爬n层楼梯 每次能走1或2步 问有几种爬法呢
找下规律 1层 1种; 2层 2种(1,1)(2);3层 3种、、、
n层只能由 n-1 或n-2的方法达到 s(n)=s(n-1)+s(n-2)
1.迭代 LTE了
public class Solution {
public int climbStairs(int n) {
if(n<=0)
return 0;
if(n==1)
return 1;
if(n==2)
return 2;
else return climbStairs(n-1)+climbStairs(n-2);
}
}
2.DP AC了
public class Solution {
public int climbStairs(int n) {
if(n<=0)
return 0;
if(n==1)
return 1;
if(n==2)
return 2;
int a=1,b=2,c=0;
for(int i=3;i<=n;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
}