爬楼梯java(leetcode70)

爬楼梯java(leetcode70):

爬楼梯java(leetcode70)

1.内存换时间的递归法:

class Solution {
    public int climbStairs(int n) {
    int memo[]=new int[n+1];
    return climbStairsmemo(n,memo);
    }
    public int climbStairsmemo(int n,int memo[]){
        if(memo[n]>0){
            return memo[n];
        }
        if(n==1){
            memo[n]=1;
        }else if(n==2){
            memo[n]=2;
        }else{
            memo[n]=climbStairsmemo(n-1,memo)+climbStairsmemo(n-2,memo);
        }
    return memo[n];
    }
}

2.动态规划:

class Solution {
    public int climbStairs(int n) {
    int climb[]=new int[n+1];
    if(n==1){
        return 1;
    }
    int i;
    climb[1]=1;
    climb[2]=2;
    for(i=3;i<=n;i++){
        climb[i]=climb[i-1]+climb[i-2];
    }
    return climb[n];
    }
}

3.斐波那契数列:


class Solution {
    public int climbStairs(int n) {
        int i,fibn;
        int first=1;
        int second=2;
        fibn=0;
        if(n==1){
            return 1;
        }
        if(n==2){
            return 2;
        }else{
        for(i=3;i<=n;i++){
            fibn=first+second;
            first=second;
            second=fibn;
        }
        }
        return fibn;
    }
}

你可能感兴趣的:(动态规划,java)