[Leetcode] Climbing Stairs 爬楼梯

本文探讨了爬楼梯问题的三种算法实现:递归、动态规划和递推法。详细解释了每种方法的时间复杂度和空间复杂度,并通过代码实例展示了如何应用这些算法解决实际问题。

Climbing Stairs

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?

递归法

复杂度

时间 O(1.618^N) 空间 O(N)

思路

这题几乎就是求解斐波那契数列。最简单的方法就是递归。但重复计算时间复杂度高。

代码

public class Solution {
    public int climbStairs(int n) {
        if(n==1 || n==0) return 1;
        else return climbStairs(n-1) + climbStairs(n-2);
    }
}

动态规划

复杂度

时间 O(N) 空间 O(N)

思路

将之前计算过的结果存下来,节省了一些时间。

代码

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

递推法 Recurrance

复杂度

时间 O(N) 空间 O(1)

思路

实际上我们求n的时候只需要n-1和n-2的值,所以可以减少一些空间啊。

代码

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

矩阵法

复杂度

时间 O(logN) 空间 O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值