leetcode: 70. Climbing Stairs

来源:互联网 发布:星际淘宝网无弹窗 编辑:程序博客网 时间:2024/06/05 22:31

Q

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 1:

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

Example 2:

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

AC

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        if n == 1:            return 1        a, b = 1, 2        for i in xrange(2, n):            tmp = b            b = a+b            a = tmp        return b# Time:  O(n)# Space: O(1)class Solution2(object):    """    :type n: int    :rtype: int    """    def climbStairs(self, n):        prev, current = 0, 1        for i in xrange(n):            prev, current = current, prev + current,        return current# Time:  O(2^n)# Space: O(n)class Solution3(object):    """    :type n: int    :rtype: int    """    def climbStairs(self, n):        if n == 1:            return 1        if n == 2:            return 2        return self.climbStairs(n - 1) + self.climbStairs(n - 2)if __name__ == "__main__":    result = Solution().climbStairs(2)    assert result == 2