LeetCode----Climbing Stairs

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?


分析:

简单的爬楼梯问题,如果这算DP题的话,那这应该是我见过的最简单DP题了。令f[i]表示到第i个楼梯时不同的方案数,f[i] = f[i - 1] + f[i - 2]。


代码:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        f = {}
        f[0] = 0
        f[1] = 1
        f[2] = 2
        i = 3
        while i <= n:
            f[i] = f[i - 1] + f[i - 2]
            i += 1
        return f[n]

你可能感兴趣的:(LeetCode,python,dp)