Pattern — Divide and Conquer
Cross-reference
Đây là alias đến Pattern-Recursion-DC focus vào D&C riêng.
Master theorem (rút gọn cho interview)
:
- với → — vd: merge sort
- → — work outside dominates
- → — work inside dominates — vd: Karatsuba
Khi D&C tốt hơn DP / Greedy?
| Tình huống | Đề xuất |
|---|---|
| Subproblems độc lập (không overlap) | D&C |
| Subproblems lồng nhau (overlapping) | DP (memoize) |
| Có greedy choice property | Greedy |
| Cần combine theo range/interval | D&C |
Top problems
| Bài | LC | Note |
|---|---|---|
| Merge Sort | — | Classic D&C + merge — backbone của Counting Inversions |
| Quick Sort | — | D&C + partition; randomize pivot |
| Quickselect | LC #215 | D&C only 1 side → avg |
| Counting Inversions | LC #493 (variant) | Merge sort + count |
| Reverse Pairs | LC #493 | Merge sort + count cặp i < j, nums[i] > 2*nums[j] |
| Maximum Subarray | LC #53 | D&C vs Kadane |
| Pow(x, n) | LC #50 | Fast exponentiation |
| Closest Pair of Points | — | |
| Median of 2 Sorted Arrays | LC #4 | D&C trên indices, |
Pitfalls
- Off-by-one trong
mid— chọn convention closed[lo, hi]hoặc half-open[lo, hi)rồi nhất quán. - Merge step thiếu i/j check: phải xử lý phần còn lại của 1 mảng khi mảng kia hết.
- Combine không O(N) → tổng phức tạp xấu hơn.
→ Nguồn: 05-Divide-and-Conquer