How to think recursively? (1)
Course: Recursion - chapter 4
This is the most challenging part. If we are given a recursive relation, it is easy to translate it into code. However, most of the time, we would have to derive the recurrence relations ourselves.
Generally, I follow a 4 step approach. Let’s take an example to understand this
Derive the recurrence relation of nCr (How many ways to choose r items out of n items?)
- **Identify the states and define the function: **First, identify what is changing with every move. It’s pretty obvious, it’s either the number of elements remaining or the number of elements we are still left to choose i.e. N and R. At any point of time, we are left with N objects and we need to choose R out of them. f(N, R) = Number of ways we can choose R objects out of N Also, our final answer should be derivable from this function. In our case, the answer is f(n, r) right?
- **Assume **that for some value of (N, R) = (x, y), f(x, y) is not calculated yet. However, every other value of f(N, R) where (N, R) ≠ (x, y), f(N, R) is already computed. So out task is to compute f(x, y) using neighboring values.
- Calculate f(x, y): What is f(x, y)? It is number of ways we can select y objects out of x objects. So currently, we have x objects and we want to choose y objects out of them. Just think of the
xthobject right now. What can we do with it? Either take it or not! If we take it, we are left with x-1 objects and we need to choose y-1 objects as we have taken thexthobject. The number of ways becomes f(x-1, y-1). If we don’t take it, we are left with x-1 objects, but we still need to choose y objects out of them. The number of ways we can do this is f(x-1, y). So overall, the total number of ways is:
f(x, y) = f(x-1, y-1) + f(x-1, y)- **Calculate the base cases: **f(0, y) = 0, f(x, 0) = 1. Think why.
And we are done 🙂
It’s very easy to write the code.
int combinations(int x, int y) { if (x == 0) return 0; if (y == 0) return 1;
return combinations(x-1, y-1) + combinations(x-1, y);}