<LeetCode><Easy> 70 Climbing Stairs #斐波那契数列

来源:互联网 发布:c stl 源码解析 pdf 编辑:程序博客网 时间:2024/04/30 02:46

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?

#Python2  TimeOut  递归     是斐波那契数列

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        return self.climbStairs(n-1)+self.climbStairs(n-2) if n>2 else 2 if n>1 else 1

#Python2 循环方式 88ms

class Solution(object):    def climbStairs(self, k):        """        :type n: int        :rtype: int        """        if not k-1:return 1        i=2        fs=[1,2]        while i<k:            fs.append(fs[-2]+fs[-1])            i+=1        return fs[-1]

#Python2  优化循环  36ms
class Solution(object):    def climbStairs(self, k):        """        :type n: int        :rtype: int        """        if k<3:return 1 if k-1==0 else 2        s0,s1=1,2        for i in range(2,k):            s1,s0=s0+s1,s1        return s1



1 0
原创粉丝点击