[LeetCode] 070. Climbing Stairs

070. 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?

Note: Given n will be a positive integer.
Example:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Solution:

class Solution1:
    """
    递归做法
    """
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        if n == 2:
            return 2
        return self.climbStairs(n-1) + self.climbStairs(n-2)


class Solution2:
    """
    非递归做法
    """
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        pre_1_step = 1
        pre_2_step = 0
        count = 1
        for i in range(1, n+1):
            count = pre_1_step + pre_2_step
            pre_2_step = pre_1_step
            pre_1_step = count
        return count

class Solution:
    """
    非递归做法,比上一个方法快
    """
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        F = [0, 1]
        count = 1
        for i in range(n):
            count = F[0] + F[1]
            F[0] = F[1]
            F[1] = count
        return count
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,864评论 0 10
  • Chapter 1 In the year 1878, I took my degree of Doctor of...
    foxgti阅读 4,098评论 0 6
  • 谢谢她——送给我们的闺蜜 文/顾二 这生活熙熙攘攘,我们却变的越加孤独。会莫名奇妙的心情烦躁,有一种坐立难安的焦...
    无平不平阅读 516评论 0 0
  • 第二章(上)初光 文/张悠扬 身子快养了一个月,伤口都已经结痂,付姿看了看镜子里的自己,若不是宫女手巧,自己这稀少...
    张悠扬阅读 774评论 1 10
  • 《君子过》 稍安坐,君醉前庭,不晓得,前景挫,自难抹。风过掠夺美誉乐,戚戚朔雪唾。 声深刻,几转阁楼,浅眉没,是哪...
    椒房不淑阅读 591评论 3 6

友情链接更多精彩内容