[MasterThe Coding Interview]Algorithms:DynamicProgramming
本篇為MasterThe Coding Interview教學影片筆記文
假設今天有一個function可以幫我們把數字加10,當我們輸入5的時候,他會輸出15,輸入3會輸出13等,儘管帶入的數字一樣,每執行一次函式,就會重新計算一次結果。如果今天這個function的計算需要花很長一段時間,透過原本的方法就會多了很多不必要的等待,這時候就可以用Dynamic programming的技巧,簡單來說就是把已經計算過的輸出記錄起來,避免掉二次、三次的重工。
1 | let cache = {} |
只要問題符合以下五個條件,就可以嘗試用Dynamic programming解決:
- Can be divided into subproblem
- Recursive Solition
- Are there repetitive subproblem
- Memoize subproblem
- Demand a raise from your boss
Exercise: Fibonacci
1 | function fibonacciMaster(){ //O(n) |