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

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

Example 2:

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

python实践

  • 斐波那契数列
  • 动态规划思想
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # 找规律,斐波那契数列
        pre = 1
        ppre = 1
        if n == 1:
            return 1
        else:
            for i in range(2, n + 1):
                tmp = pre
                pre = ppre +pre
                ppre = tmp
            return pre

    def climbStairs2(self, n):
        # 定义到第i个台阶,可能的情况数
        if n == 1 or n == 2:
            return n
        else:
            dp = [0]*(n+1)
            dp[1] = 1
            dp[2] = 2
            for i in range(3, n+1):
                dp[i] = dp[i-1] + dp[i-2]
            return dp[-1]


s = Solution()
s2 = s.climbStairs2(5)
print(s2)

类似问题

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦