DSA · Beginner · Pattern 7 of 11
Recursion
11 problems.
Your progress0%
- 1st Visit
- 0/11
- 2nd Visit
- 0/11
- Revise
- 0/11
About this pattern
A recursive function solves a problem by calling itself on smaller instances until it reaches a base case that is answered directly. Writing one comes down to three decisions: the base case, the smaller subproblem, and how to combine its result into the answer.
The pattern appears when a structure is defined in terms of itself (sequences, grammars, nested expressions), when the input can be halved as in fast exponentiation, or when every subset or sequence of choices must be enumerated for a small n, around 20 or fewer. Cost is the number of calls times the work per call; exponential enumeration is acceptable only for small inputs, and very deep recursion consumes stack memory.
// Shape of a recursive function.
long long solve(long long n) {
if (n <= 1) return baseValue(n); // 1. base case
long long sub = solve(n / 2); // 2. smaller instance
return combine(sub, n); // 3. combine
}
// Enumerate all 2^n include/exclude choices.
void go(int i, const vector<int>& a, long long sum) {
if (i == (int)a.size()) { check(sum); return; }
go(i + 1, a, sum + a[i]); // take a[i]
go(i + 1, a, sum); // skip a[i]
}