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?

简单的一维动态规划问题。但是印象颇为深刻,当时保研机试的时候考过这题,当时非计算机出生的我连动规是什么都不知道,自此引出笔试超高,机试超差的结局,还好后来现在的导师主动找我,被录了。话说回来,这题虽然是一维动规,但是其实质是斐波那契数列,即根据最后一步可以是跨两步或者跨一步,f(n)=f(n-1)+f(n-2)。用迭代或者递归都可以解,并且实际并不需要像通常的DP问题,需要O(n)的空间保存结果,只需要前两步的结果。因此用常数空间就可以解决。时间复杂度为O(n),空间复杂度O(1).

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<=1: return 1
        f1 = f2 =1

        for i in range(2,n+1):
           f3 = f1+f2
           f1 = f2
           f2 = f3
        return f3 

另斐波那契数列存在O(logn)的解法。根据斐波那契的通项公式:

c6dc35b68545005b9b6fa6995c4f6d52.png

原文地址:https://www.cnblogs.com/sherylwang/p/5448936.html