70.爬楼梯(C++)

题目英文描述:
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 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

代码(动态规划)(O(n)):

class Solution {
public:
    int climbStairs(int n) {
        int first = 0, second = 0, third = 1;
        for(int i = 1; i <= n; ++i) {
            first = second;
            second = third;
            third = first + second;
        }
        return third;
    }
};

代码(斐波那契数列通项公式)(O(logn)):


斐波那契数列通项公式
class Solution {
public:
    int climbStairs(int n) {
        double sqrt5 = sqrt(5);
        double fibn = pow((1 + sqrt5)/2, n + 1) - pow((1 - sqrt5)/2, n+1);
        return (int)(fibn / sqrt5);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。