Overview of recursion¶
Content summary
This lesson covers recursion, including: - The concept - The general structure of a recursive function
Concept¶
Some problems can be broken down into smaller, similar subproblems.
Recursion takes advantage of this by solving the original problem through solving these smaller subproblems.
Recursion is a programming technique where a function calls itself to solve the original problem.
General structure of a recursive function¶
In a recursive function, we must define two types of cases:
-
Base case
This is a subproblem that can be solved directly, without further recursion.
When this case is reached, the recursion stops.
In other words, if the base case is not defined, recursion will continue forever, causing stack overflow (memory error), and the problem will never be solved.
-
Recursive case
This defines how the function calls itself with a smaller version of the problem. Usually, we use a recurrence relation to make the recursive call.
Each recursive call brings us closer to the base case. Recursion ends when the base case is reached.
A recursive function can be written in this general form:
def recursive_function(n):
# Base case
if n is base_case:
return some_base_value
# Recursive case
return recursive_function(simpler_n)
Some problems solved using recursion¶
Here are common problems that can be solved with recursion:
- Factorial: \(n!\)
- Fibonacci sequence
- Tower of Hanoi
- Power: \(a^n\)
- Greatest Common Divisor (GCD) using Euclid’s algorithm
- Reverse a string
- Check if a string is a palindrome
- Generate permutations or combinations
- N-Queens problem
- Divide-and-conquer algorithms: quick sort, merge sort
- Binary tree traversal: preorder, postorder, inorder
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| đệ quy | recursion |
| trường hợp cơ sở | base case |
| trường hợp đệ quy | recursive case |