FANFNA
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # DP [TOC] ## 2.1 動態規劃簡介 :::success **動態規劃(Dynamic Programming)** 是指將一個較大的問題定義為較小的子問題組合,先處理較小的問題並將結果儲存起來(通常使用表格),再進一步以較小問題的解逐步建構出較大問題的解。 ::: :::info 動態規劃需合於 principle of optimality (Bellman 1957) An optimal sequence of decisions has the property that whatever the initial state and decision are, the remaining decisions must constitute an optimal decision with regard to the state resulting from the first decision. ::: ### 與其他演算法設計哲學比較 :::info - Divide-and-Conquer:Divide-and-Conquer 和 Dynamic Programming都是將問題切割再採用遞迴方式處理子問題,但是Divide-and-Conquer子問題的解通常不會重覆,重複時,通常會對相同子問題進行重覆計算,而不會像Dynamic Programming的子問題有大量的重複(overlap),可以以table儲存不用再次計算,用空間換取時間。 ::: :::info - Greedy Approach:Greedy Approach具有Selection Procedure,自某起始點開始在每一個階段逐一檢查每一個輸入是否適合加入答案中。如果所要處理的最佳化問題無法找到一個選擇程序來逐一檢查,而需要以一次考慮所有的可能情況的方式來處理,那就是屬於Dynamic Programming。因此若遇最佳化問題,先思考可否用Greedy Approach解,若不行再考慮Dynamic Programming。 ::: ## 2.2 經典動態規劃問題 ### Shortest path problem in weighted directed graph :::success **(negative edge allowed but no negative cycles)** :::info - 定義:對多階段圖,求最短路徑 解法 (forward approach) ![](https://i.imgur.com/m8zZmf3.png) f(k)表示狀態 k 到終點狀態的最短距離。 :::warning - 初始條件:f(k)=0 - 遞迴式:f(k−1)=min{f(k)+W(k−1,k)},其中W(k−1,k)表示狀態k−1到狀態k的距離 ::: 複雜度分析 :::info - 時間複雜度 : O(|V|+|E|) - 空間複雜度 : Table儲存Costi(j)需O(|V|),但輸入Graph需O(|V|+|E|) ::: :::warning - 計算概念補充 : 對多階段圖求最短路徑有 forward approach 和 backward approach 兩種,以 forward approach 來說,遞迴式的展開方向 forward ,也就是V0→Vd,但是解題時因為是用 bottom-up 的方式累積解答,所以數字要從Vd開始寫,一直累積到V0結束。 ::: ### Chained Matrix Multiplication Problem :::success - 定義:給定Matrix Chain : A1(d0,d1),A2(d1,d2),...,An(dn−1,dn),求此Chain所需之乘法次數為最少之括號方式 A1(3,5)表示第一個矩陣是3乘4的矩陣,注意A和d足碼之間的關係! n 個 matrix 相乘有 $C_n = \frac{1}{n+1}{2n \choose n} = \frac{(2n)!}{(n+1)!n!}$種可能的配對組合,這個數很有名,又稱卡塔蘭數([Catalan number](https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0))。 ![](https://i.imgur.com/08AJHcS.png) :::warning 我們排列組合中會用到 ::: :::info - 解法 ![](https://i.imgur.com/IPcTDhr.png) 複雜度分析 - 空間複雜度 : 當n個矩陣會有約$\frac{n^2}{2}$個不同的子序列。 - 時間複雜度 : 可證明此一簡單的技術可使得運算時間由O(2^n^)降至O(n^3^),使得其對實際應用有足夠的效率。 :::warning - 例題:A1(3×3),A2(3×7),A3(7×2),A4(2×9),A5(9×4), 求此五矩陣的最小乘法次數。 *要會把切割點表格(右下P表格)轉成實際的乘法順序,也就是乘法順序樹,再次提醒,注意A和d足碼之間的關係。 ![](https://i.imgur.com/8R9h1rn.png) ![](https://i.imgur.com/v5x9BlW.png) ![](https://i.imgur.com/PNA0XHj.png) ![](https://i.imgur.com/ghmnWMj.png) ![](https://i.imgur.com/iI2rMPU.png) ::: ### The Longest Common Subsequence (LCS) Problem :::success [參考](https://www.programiz.com/dsa/longest-common-subsequence) - 定義:給定兩個`Sequence` X=<x1,x2,...,xm>和Y=<y1,y2,...,yn>,求X和Y所構成的最長共同子序列LCS(X,Y)=Z=<z1,z2,...,zk> 為何 ? ::: :::danger - **[注意]** `Substrings`和`Subsequences`的差別 - String:a segment of `consecutive` characters. - Sequence:need not be `consecutive`. ::: :::warning 例如有一條字串(String) S = `"a t g a t g c a a t"`,則 Substrings of S : `"g a t g c"` , `"t g c a a t"` Subsequences of S : "a g g t" , "a a a a" ::: :::info 解法 ![](https://i.imgur.com/eWftOR8.png) - 若 i 或 j 為 0,表示 X 或 Y 這兩條序列的其中一條為空序列。 - 若 x~i~=y~j~ ,則c[i,j]所表示的序列長度,是由`<x1,x2,...,xi−1>`和`<y1,y2,...,yj−1>`兩序列所構成之最長共同子序列的長度,**即`c[i−1,j−1]`**)再加上1。 - 若 xi≠yj,則c[i,j]的序列長度是由下列兩個不同的最長共同子序列長度當中之最大值所構成: 1. `<x1,x2,...,xi−1>` 和 `<y1,y2,...,yj>` 兩序列所構成之最長共同子序列的**長度`c[i−1,j]`** 2. `<x1,x2,...,xi>` 和 `<y1,y2,...,yj−1>` 兩序列所構成之最長共同子序列的**長度`c[i,j−1]`** :::warning - 例題:shows the tables produced by **LCS-LENGTH** on the sequences $X$ = 〈`A, B, C, B, D, A, B`〉 and $Y$ = 〈`B, D, C, A, B, A`〉. - The running time of the procedure is O(mn), since each table entry takes O(1) time to `compute`. ::: ![](https://i.imgur.com/XX6xhrL.png =400x300)![](https://i.imgur.com/44ffITx.png =200x100) ![](https://i.loli.net/2020/04/07/XpuyFOMH6jJYdxT.gif) :::info - LCS的應用 Longest increasing subsequence `Y ← Sort(X); //Y具有遞增性` `Z ← LCS(X, Y); //找出X與Y間的最長共同子序列且具有遞增性` Longest common substring:計算連續的「左上箭頭」有多長 ``` =c c[i, j] = 1 + c[i-1,j-1] , if x=y = 0,otherwise ``` ::: ### 0/1 Knapsack problem :::success - 定義:有 n 種物品,物品 j 的重量為wj價格為pj。我們假定所有物品的重量和價格都是非負的。背包所能承受的最大重量為W。如果限定每種物品只能選或不選(0或1),在總重量不超過W的前提下,我們希望總價格最高,則此問題稱為0/1背包問題。 ::: :::info - 解法:我們將在總重量不超過Y的前提下,總價格所能達到的最高值定義為A(Y)。A(W)即為問題的答案。A($j,Y$)的遞推關係為: 1. A(0,Y)=0 2. A(j,0)=0 3. w~j~>Y,A(j,Y)=A(j−1,Y) 4. w~j~≦Y,A(j,Y)=max{A(j−1,Y),pj+A(j−1,Y−w~j~)} - 通過計算A(n,W)即得到最終結果。 - 3.的意思是,第j項物品根本拿不起來。 - 4.的意思是,要維持原本拿的東西,或是放下其中一樣東西拿起新的第j項物品。 ::: :::info - 複雜度分析 : 時間和空間皆為O(nW)。若重量剛好為順序資料,則時間複雜度為 O(n^2^),空間複雜度為 O(n)。 - 重要概念 : 儘管背包問題的時間複雜度為O(nW),但它仍然是一個NP完全問題。這是因為一般化的重量W相對於整個問題的輸入大小並不成線性關係,而是logW(也就是W表示成binary所需要的bit數)。因此整個演算法針對input size的複雜度為O(n×2^logW^)=O(n×2^n^)。 :::success - 例題:Item = {weight, value}, - C = [{4,5},{2,5},{6,2},{5,4},{3,3},{5,4},{2,3},{5,7}] ::: :::warning ![](https://i.imgur.com/MsvKF6S.png) ::: :::warning 另外一種背包問題,Fractional Knapsack Problem,物品可切割的情況,則可用Greedy algorithm求解,因為一直選取區域最佳解可以構成全域最佳解。 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully