[leetcode]Climbing Stairs @ Python


原題地址:https://oj.leetcode.com/problems/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?

解題思路:

爬樓梯問題。經典的動態規划問題。每次上一個台階或者兩個台階,問一共有多少種方法到樓頂。這個實際上就是斐波那契數列的求解。可以逆向來分析問題,如果有n個台階,那么走完n個台階的方式有f(n)種。而走完n個台階有兩種方法,先走完n-2個台階,然后跨2個台階;先走完n-1個台階,然后跨1個台階。所以f(n) = f(n-1) + f(n-2)。

代碼:

class Solution:
    # @param n, an integer
    # @return an integer
    def climbStairs(self, n):
        dp = [1 for i in range(n+1)]
        for i in range(2, n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM