分治法基礎
分治法(Divide and Conquer)顧名思義,思想核心是將問題拆分為子問題,對子問題求解、最終合並結果,分治法用偽代碼表示如下:
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,圖示如下:
和動態規划、貪心等一樣,分治法是一種算法思想,不是用於解決專門某類問題的方法。折半查找(Binary Search)、快速排序/快速選擇/歸並排序、二叉樹處理等都包含了分治法的思想。
關於折半查找、快速排序/歸並排序,詳見:
算法與數據結構基礎 - 折半查找(Binary Search)
相關LeetCode題:
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 題解
時間復雜度
分治法中常用到遞歸,因而其時間復雜度並不直觀,關於分治法時間復雜度計算,詳見:
Advanced master theorem for divide and conquer recurrences