Divide and Conquer
Break a problem into roughly equal sized subproblems, solve seperately, and combine results.
Video: https://www.youtube.com/watch?v=2Rr2tW9zvRg
Two steps:
- Split problem to sub-problems
- Combine sub-results to final result
1 | DAC(p): |
Topics
- Binary Searxh
- Finding Maximum and Minimum
- Merge Sort
- Quick Sort
- Strassem’s Matrix Multiplication
Usually solved with recursion.
50. Pow(x, n)
Leetcode: https://leetcode.com/problems/powx-n/description/
- If use normal recursive solution, will raise stackOverFlow error
- Solution: Divide the pow into x^ (n/2) * x ^ (n/2)
1 | class Solution { |
241. Different Ways to Add Parentheses
[Solution]
- Iterate through the input string, if meet operator, split it to left half and right half
- Combine the computation results from left half and right half, append them to the result list
1 | # Input: <str> number, +, -, * |
222. Count Complete Tree Nodes
Leetcode: https://leetcode.com/problems/count-complete-tree-nodes/
Note:
- Check whether the height of the left sub-tree equals to the right sub-tree
- If equal, then the last node would be in the right subtree, and the number of nodes in the left sub-tree would be
pow(2, height - 1) - 1
, add one root node, would bepow(2, height - 1)
. Then we recursively calculate the number of nodes in the right sub-tree - If not equal, then the last node would be in the left sub-tree.
1 | def countNodes(self, root): |
493. Reverse Pairs
Leetcode: https://leetcode.com/problems/reverse-pairs/
Greate reading: https://leetcode.com/problems/reverse-pairs/discuss/97268/General-principles-behind-problems-similar-to-%22Reverse-Pairs%22
1 | def reversePairs(self, nums: List[int]) -> int: |
23. Merge k Sorted Lists
Leetcode: https://leetcode.com/problems/merge-k-sorted-lists/
1 | def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: |