[LeetCode]--70. 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?这是一个很经典的爬楼梯问题,面试也会经常遇

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?

这是一个很经典的爬楼梯问题,面试也会经常遇见。经过推演:
这是一个动态规划的题目:
n = 1 时 ways = 1;
n = 2 时 ways = 2;
n = 3 时 ways = 3;

n = k 时 ways = ways[k-1] + ways[k-2];

明显的,这是著名的斐波那契数列问题。有递归和非递归两种方式求解,但是亲测递归方式会出现 The Time Limit异常,所以只能采用非递归计算,可以用一个动态数组保存结果。

我最开始想到的是递归,写法简单,也容易理解,不过算了几次都是超时不能通过。

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

后来写了非递归算法。

public int climbStairs1(int n) {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else if (n == 2)
            return 2;

        int[] r = new int[n];
        //其余的情况方式总数 = 最终剩余1层的方式 + 最终剩余两层阶梯的方式
        r[0] = 1;
        r[1] = 2;

        for (int i = 2; i < n; i++)
            r[i] = r[i - 1] + r[i - 2];

        int ret = r[n - 1];
        return ret;
    }

这种就通过了。这个题目关键要想到斐布那契数列。

再提供一种不用数组的写法。

public int climbStairs2(int n) {
        if (n <= 1) {
            return 1;
        }
        int last = 1, lastlast = 1;
        int now = 0;
        for (int i = 2; i <= n; i++) {
            now = last + lastlast;
            lastlast = last;
            last = now;
        }
        return now;
    }
目录
相关文章
LeetCode 70. 爬楼梯 Climbing Stairs
LeetCode 70. 爬楼梯 Climbing Stairs
LeetCode 70. Climbing Stairs
你正在爬楼梯。 它需要n步才能达到顶峰。 每次你可以爬1或2步。 您可以通过多少不同的方式登顶? 注意:给定n将是一个正整数。
40 0
LeetCode 70. Climbing Stairs
LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50514606 翻译 你正在爬一个楼梯。
911 0
|
C++ Python
[LeetCode] Climbing Stairs
Note: If you feel unwilling to read the long codes, just take the idea with you. The codes are unnecessarily long due to the inconvenient handle of matrices.
686 0
|
算法 Python
leetcode 70 Climbing Stairs
 Climbing Stairs                       You are climbing a stair case. It takes n steps to reach to the top.
1099 0
|
机器学习/深度学习
|
21天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3