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
    原文作者:TurtleLin
    原文地址: https://segmentfault.com/a/1190000015739267
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞