272. 爬楼梯 II

272. 爬楼梯 II

中文English

一个小孩爬一个 n 层台阶的楼梯。他可以每次跳 1 步, 2 步 或者 3 步。实现一个方法来统计总共有多少种不同的方式爬到最顶层的台阶。

样例

Example 1:

Input: 3
Output: 4
Explanation: 1 + 1 + 1 = 2 + 1 = 1 + 2 = 3 = 3 , there are 4 ways.

Example 2:

Input: 4
Output: 7
Explanation: 1 + 1 + 1 + 1 = 1 + 1 + 2 = 1 + 2 + 1 = 2 + 1 + 1 = 2 + 2 = 1 + 3 = 3 + 1 = 4 , there are 7 ways.

说明

对于n=0,我们认为答案是1。

class Solution:
    """
    @param n: An integer
    @return: An Integer
    """
    def climbStairs2(self, n):
        # write your code here
        if not n: return 1 
        
        dp = [0 for i in range(n + 1)]
        for i in range(n + 1):
            if i in [0, 1]:
                dp[i] = 1 
            elif i == 2:
                dp[i] = 2 
            elif i == 3:
                dp[i] = 4
            else:
                dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] 
        
        return  dp[n]

 

posted @ 2021-01-11 00:32  风不再来  阅读(152)  评论(0编辑  收藏  举报