题目来自:https://leetcode-cn.com/problems/climbing-stairs/
参考:
https://www.cnblogs.com/xiaolovewei/p/8072489.html
分析:
爬到n,可以是从n-1级楼梯一次爬上来,也可以是从n-2级一次走两步上来(不能从n-2走一步再走一步,因为走一步就会去到n-1级,重复)。所以有公式f(n)=f(n-1)+f(n-2)
递推解:
class Solution {
public int climbStairs(int n) {
int[] dbNum = new int[n+3];
dbNum[1] = 1;
dbNum[2] = 2;
for(int i=3;i<=n;i++){
dbNum[i]=dbNum[i-1]+dbNum[i-2];
}
return dbNum[n];
}
}
动态规划:
class Solution {
static int[] dbNum ;
public static int db(int num){
if(num==1){
return 1;
}
if(num==2){
return 2;
}
if(dbNum[num]>0){
return dbNum[num];
}
dbNum[num]=db(num-1)+db(num-2);
return dbNum[num];
}
public int climbStairs(int n) {
dbNum = new int[n+1];
return db(n);
}
}