LeetCode 70: 爬楼梯

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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps
    Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
3. 1 step + 1 step + 1 step
4. 1 step + 2 steps
5. 2 steps + 1 step
这是一个爬楼梯问题,自己18年在面试小米公司的时候遇到过,当时听完面试官说这道题的时候自己一脸懵逼,面试官后来讲完解题思路自己才有点恍然大悟,昨天在回京的火车上又看到这道题,今天记录一下。
这个问题实际上跟斐波那契数列非常相似,假设梯子有n层,那么如何爬到第n层呢,因为每次只能爬1或2步,那么爬到第n层的方法要么是从第 n-1 层一步上来的,要不就是从 n-2 层2步上来的,所以递推公式非常容易的就得出了:dp[n] = dp[n-1] + dp[n-2]。
Java 解法一:

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

        return dynamicArray[n];
    }

我们可以对空间进行进一步优化,只用两个整型变量a和b来存储过程值,首先将 a+b 的值赋给b,然后a赋值为原来的b,所以应该赋值为 b-a 即可。这样就模拟了上面累加的过程,而不用存储所有的值,参见代码如下:
Java解法2:

public class Solution {
    public int climbStairs(int n) {
        int a = 1, b = 1;
        while (n-- > 0) {
            b += a; 
            a = b - a;
        }
        return a;
    }
}

或者

 public static int climbStairs4(int n) {
            int a = 1, b = 1;
            while (--n > 0) {
                b += a;
                a = b - a;
            }
            return b;
        }

当然还有使用数组做缓存的方法
Java解法3

public class ClimbingStairs {

    public static int climbStairsWithRecursionMemory(int n) {
        int[] memoryArray = new int[n + 1];
        return subClimbStairsWithRecursionMemory(n - 1, memoryArray) + subClimbStairsWithRecursionMemory(n - 2, memoryArray);

    }

    public static int subClimbStairsWithRecursionMemory(int n, int[] memoryArray) {
        if (n == 1) {
            return 1;
        } else if (n == 2) {
            return 2;
        } else {
            if (memoryArray[n] > 0) {
                return memoryArray[n];
            }
            memoryArray[n] = subClimbStairsWithRecursionMemory(n - 1, memoryArray) + subClimbStairsWithRecursionMemory(n - 2, memoryArray);

            return memoryArray[n];
        }
    }
}

另外还有其他方法
参考文章 算法:Climbing Stairs(爬楼梯) 6种解法
70. Climbing Stairs 爬楼梯问题
https://leetcode.com/problems/climbing-stairs/solution/

发布了80 篇原创文章 · 获赞 140 · 访问量 64万+

猜你喜欢

转载自blog.csdn.net/linjpg/article/details/104754312