recursion
recursion
function solves a problem by calling itself with a smaller or simpler version of the
original problem. It's especially useful for problems that can be broken down into similar
subproblems, which makes it a natural fit for tasks involving repetition, hierarchy, or
self-similar patterns.
1. Base Case – This is the condition that tells the function to stop calling itself. It
prevents infinite recursion and eventually returns a result without making further
recursive calls.
2. Recursive Case – This is where the function calls itself, usually with a smaller or
reduced version of the original input, gradually working toward the base case.
When the function runs, it keeps calling itself until it reaches the base case. At that point,
it begins to return values back up the chain of calls, eventually producing the final result.
Example
java
CopyEdit
int factorial(int n) {
Advantages:
Disadvantages:
● Risk of stack overflow if the recursion depth is too large or the base case is
missing.
Optimizing Recursion
To deal with inefficiency, especially in cases where the same subproblem is solved
multiple times, techniques like:
● Dynamic Programming
● Tail Recursion (where possible, some languages optimize tail-recursive calls)