70. Climbing Stairs

Problem:

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.


题意很简单,就是给定台阶数,然后每次可以走一步或者两步,问有多少种走法。台阶数大于0。其实这题的结果是一个除去第一项的斐波那契数列,结果是1, 2, 3, 5, 8, 13等等。结果等于前两项的和。一开始想着用递归解决,比较简单。如Code1,发现too young too simple too navie,超时了。

后来就打算换一种方法,一种复杂度为O(n)的方法。就是矩阵运算。

[f(1)]   [0][1]   [f(0)]             [f(n-1)]   [0][1]   [f(n-2)]

       =          *          ……               =        *

[f(2)]   [1][1]   [f(1)]             [f(n)]      [1][1]   [f(n-1)]

然后结果为Code2。


Code1:

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


Code2(LeetCode运行3ms):

class Solution {
public:
    int climbStairs(int n) {
        int Matrix[4] = {0, 1, 1, 1};
        int step[2] = {0, 1};
        for (int i = 0; i < n; i++) {
            MultiplyMatrix(Matrix, step);
        }
        return step[1];
    }
    void MultiplyMatrix(int Matrix[], int step[]) {
        int s1 = step[0] * Matrix[0] + step[1] * Matrix[1];
        int s2 = step[0] * Matrix[2] + step[1] * Matrix[3];
        step[0] = s1;
        step[1] = s2;
    }
};

再次看回这道题,打算再用一个更简单的方法去解决:通过数学归纳法解出斐波那契数列的通项公式:


所以直接用cmath头文件里的函数就能解决问题,复杂度是O(1)。


Code3(LeetCode运行0ms):

class Solution {
public:
    int climbStairs(int n) {
	double factor = sqrt(5);
    	return floor((pow((1 + factor) / 2, n + 1) + pow((1 - factor) / 2, n + 1)) / factor + 0.5);
    }
};


这一题还有一个比较经典、通用的的做法,就是动态规划。假设楼梯有6个台阶。那么想一下要达到最后一个台阶,前一个状态是什么?可以是在第5个台阶,这时候再走一步就到了。或者在第4个台阶,然后再走两个台阶。所以就是F(6)=F(5) + F(4)。所以状态转移方程是:

1. F(i) = i   (i <= 2)

2. F(i)  = F(i-1) + F(i-2) (i > 2)

所以这就是上面斐波那契解法的由来,动态规划更通用,因为可能步数是可以是其他的取值的。而动态规划还有一个点就是如何去处理转移方程,有人看到式子就会想到递归。但是上面已经写过了,超时了。原因递归的时候是有很多重复的求值过程。例如F(6) = F(5)+F(4), F(5) = F(4)+F(3), 这里F(4)就重复求值了。所以递归超时了,而这里最好用的就是递推,并且保存下前面求出的值。这题比较简单,只要两个变量就能保存。


Code3(LeetCode运行0ms):

class Solution {
public:
    int climbStairs(int n) {
        int result = 0;
        int temp;
        for (int i = 1; i <= n; i++) {
            if (i <= 2) {
                temp = result;
                result = i;
            } else {
                int tmp = result;
                result = temp + result;
                temp = tmp;
            }
        }
        return result;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值