[算法笔记] 爬楼梯
70.爬樓梯 https://leetcode-cn.com/problems/climbing-stairs/
假設(shè)你正在爬樓梯。需要 n?階你才能到達(dá)樓頂。
每次你可以爬 1 或 2 個(gè)臺(tái)階。你有多少種不同的方法可以爬到樓頂呢?
注意:給定 n 是一個(gè)正整數(shù)。
示例 1:
輸入: 2 輸出: 2 解釋: 有兩種方法可以爬到樓頂。 1. 1 階 + 1 階 2. 2 階示例 2:
輸入: 3 輸出: 3 解釋: 有三種方法可以爬到樓頂。 1. 1 階 + 1 階 + 1 階 2. 1 階 + 2 階 3. 2 階 + 1 階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 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 stepsExample 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?
Constraints:
- 1 <= n <= 45
題解:
1. 動(dòng)態(tài)規(guī)劃法求解:
本問(wèn)題其實(shí)常規(guī)解法可以分成多個(gè)子問(wèn)題,爬第n階樓梯的方法數(shù)量,等于 2 部分之和:a. 爬上` n-1` 階樓梯的方法數(shù)量q。因?yàn)樵倥?階就能到第n階b. 爬上` n-2` 階樓梯的方法數(shù)量p。因?yàn)樵倥?階就能到第n階 所以我們得到公式 r = p + q 同時(shí)需要初始化 r=1 和p=0,q=0。 注意:初始值的設(shè)置和循環(huán)條件有關(guān)系。時(shí)間復(fù)雜度:O(n)
C語(yǔ)言解法:
2. 斐波那契數(shù)列
如果觀察數(shù)學(xué)規(guī)律,可知本題是斐波那契數(shù)列,那么用斐波那契數(shù)列的公式即可解決問(wèn)題,公式如下:
時(shí)間復(fù)雜度:O(logn)
Java實(shí)現(xiàn):
class Solution {public int climbStairs(int n) {double sqrt_5 = Math.sqrt(5);double fib_n = Math.pow((1 + sqrt_5) / 2, n + 1) - Math.pow((1 - sqrt_5) / 2,n + 1);return (int)(fib_n / sqrt_5);} }聲明:感謝畫手大鵬提供的思路: https://leetcode-cn.com/problems/climbing-stairs/solution/hua-jie-suan-fa-70-pa-lou-ti-by-guanpengchn/
總結(jié)
以上是生活随笔為你收集整理的[算法笔记] 爬楼梯的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [算法笔记]-环形链表Ⅱ-解题方法
- 下一篇: [算法笔记]二叉树基础