分治法基礎html
分治法(Divide and Conquer)顧名思義,思想核心是將問題拆分爲子問題,對子問題求解、最終合併結果,分治法用僞代碼表示以下:git
function f(input x size n) if(n < k) solve x directly and return else divide x into a subproblems of size n/b call f recursively to solve each subproblem Combine the results of all sub-problems
分治法簡單而言分三步 Divide、Conquer、Combine,圖示以下:github
和動態規劃、貪心等同樣,分治法是一種算法思想,不是用於解決專門某類問題的方法。折半查找(Binary Search)、快速排序/快速選擇/歸併排序、二叉樹處理等都包含了分治法的思想。算法
關於折半查找、快速排序/歸併排序,詳見:緩存
算法與數據結構基礎 - 折半查找(Binary Search)數據結構
相關LeetCode題:spa
215. Kth Largest Element in an Array 題解
426. Convert Binary Search Tree to Sorted Doubly Linked List 題解
4. Median of Two Sorted Arrays 題解
緩存過程結果(Memoization)
一些場景下咱們會遇到相同的子問題,這時能夠用哈希表等結構緩存子問題的結果,當再次遇到相同子問題時、直接返回結果便可,memoization是經常使用的減小計算複雜度的技巧。
相關LeetCode題:
241. Different Ways to Add Parentheses 題解
時間複雜度
分治法中經常使用到遞歸,於是其時間複雜度並不直觀,關於分治法時間複雜度計算,詳見: