LeetCode第70题:爬楼梯(简单)

LeetCode第70题:爬楼梯(简单)

  • 题目:假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?注意:给定 n 是一个正整数。
  • 思路一:斐波那契额数列,想用递归解决问题。但是超出了时间限制。
class Solution {
    public int climbStairs(int n) {
        if(n==1){
            return 1;
        }else if(n==2){
            return 2;
        }else{
            return climbStairs(n-1)+climbStairs(n-2);
        }
    }
}
  • 思路二:递归每一步存在冗余,就想到了用数组存储的方式。
class Solution {
    public int climbStairs(int n) {
        int ans[] = new int[n];
        if(n==1) return 1;
        ans[0]=1;
        ans[1]=2;
        for(int i=2;i<n;i++){
            ans[i]=ans[i-1]+ans[i-2];
        }
        return ans[n-1];
    }
}

在这里插入图片描述

  • 思路三:官方给出的一种解法是用斐波那契数列公式直接求,其实我觉得挺无聊的。。。
public class Solution {
    public int climbStairs(int n) {
        double sqrt5=Math.sqrt(5);
        double fibn=Math.pow((1+sqrt5)/2,n+1)-Math.pow((1-sqrt5)/2,n+1);
        return (int)(fibn/sqrt5);
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了79 篇原创文章 · 获赞 7 · 访问量 1369

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104410448
今日推荐