算法与数据结构基础 - 分治法(Divide and Conquer)

分治法基础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)数据结构

算法与数据结构基础 - 排序(Sort)ide

 

相关LeetCode题:spa

169. Majority Element  题解code

53. Maximum Subarray  题解htm

215. Kth Largest Element in an Array  题解

426. Convert Binary Search Tree to Sorted Doubly Linked List  题解

240. Search a 2D Matrix II  题解 

218. The Skyline Problem  题解

4. Median of Two Sorted Arrays  题解 

 

缓存过程结果(Memoization)

一些场景下咱们会遇到相同的子问题,这时能够用哈希表等结构缓存子问题的结果,当再次遇到相同子问题时、直接返回结果便可,memoization是经常使用的减小计算复杂度的技巧。

 

相关LeetCode题:

241. Different Ways to Add Parentheses  题解

312. Burst Balloons  题解

 

时间复杂度

分治法中经常使用到递归,于是其时间复杂度并不直观,关于分治法时间复杂度计算,详见:

Advanced master theorem for divide and conquer recurrences

相关文章
相关标签/搜索