解题思路

动态规划:f(n) = f(n-1) + f(n-2)
因为每一阶只需要维护一个状态,所以采用三个变量向后滚动就足够了,从而优化存储空间。

代码

class Solution {
public:
    int jumpFloor(int number) {
        if (number == 1)
            return 1;
        if (number == 2)
            return 2;

        int a = 1, b = 2;
        int c;
        for (int i = 3; i <= number; ++i) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};