[Lintcode]111. Climbing Stairs/[Leetcode]70. Climbing Stairs

111. Climbing Stairs/70. Climbing Stairs

  • 本题难度: Easy
  • Topic: Dynamic Programming

Description

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?

Example
Example 1:
Input: n = 3
Output: 3

Explanation:
1) 1, 1, 1
2) 1, 2
3) 2, 1
total 3.

Example 2:
Input: n = 1
Output: 1

Explanation:  
only 1 way.

我的代码

class Solution:
    """
    @param n: An integer
    @return: An integer
    """
    def climbStairs(self, n):
        if n<3:
            return n
        pre1 = 1
        pre2 = 2
        n = n-2
        while(n):
            n = n-1
            tmp = pre2
            pre2 += pre1
            pre1 = tmp
        return pre2

思路
只与前两步有关

  • 时间复杂度
  • 出错
posted @ 2019-02-16 16:03  siriusli  阅读(92)  评论(0编辑  收藏  举报