Authored by Tony Feng
Created on April 2nd, 2022
Last Modified on April 2nd, 2022
Understanding Recursion
Intro
- Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.
- Memoization could be used to save computational time.
Components of Recursion
- Base Case
- The point where you stop applying the recursive case
- Recursive Steps
- Divide the problem into one or more simpler or smaller parts of the problem;
- Call the function (recursively) on each part;
- Combine the solutions of the parts into a solution for the problem.
Characteristics
- Advantages of Recursion
- Recursive functions make the code look clean and elegant.
- A complex task can be broken down into simpler sub-problems using recursion.
- Sequence generation is easier with recursion than using some nested iteration.
- Disadvantages of Recursion
- Sometimes the logic behind recursion is hard to follow through.
- Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
- Recursive functions are hard to debug.
Examples
The Factorial of an Integer
|
|
Leetcode 509 Fibonacci Number
|
|
Leetcode 206 Reverse Linked List
|
|
Reference
- 手把手带你刷Leetcode力扣 - 递归 Recursion
- 手把手带你刷Leetcode力扣 - 力扣509
- 手把手带你刷Leetcode力扣 - 力扣206
- Programiz - Python Recursion
- WTF is Memoization