爬楼梯问题。给定 n steps can reach the top。其实就是说n阶楼梯
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
1.递归法
最开始知道的是递归方法 因为最简单。然而时间复杂度超出限制。。。 JAVA实现。
public class Solution {
public int climbStairs(int n) {
if(n==0)
return 0;
else if(n==1)
return 1;
else if(n==2)
return 2;
return climbStairs(n-1)+ climbStairs(n-2);
}
}
public int climbStairs(int n) {
if(n==0)
return 0;
else if(n==1)
return 1;
else if(n==2)
return 2;
return climbStairs(n-1)+ climbStairs(n-2);
}
}
2.迭代法