Problem Solving Fundamentals · Recursion

What recursion is

recursion

What recursion is

You are handed a stack of nesting dolls and asked to count every doll. You open the outer doll, find a smaller one inside, and open that. It holds yet another, and the task never stops looking like the task you did a moment ago.

Each doll opens to reveal a smaller doll, built the same way, until one is solid. You do not need a fresh plan for every layer. You count the doll in your hand, see that it holds one more of the same thing, and hand that inner doll to the same plan. The work repeats on something smaller. That repeat is what recursion names.

Two things have to be true for it to end. One doll has to be solid — a case you can answer without opening anything, the base case. And each step has to leave less to open than the one before, so you actually reach it.

The rest is a leap of faith. When you call the function on the smaller doll, you assume that call already returns the right count. You only do the small piece in front of you: count this doll and trust the call to handle the rest. A function that calls itself this way is recursive.

You are about to answer a quiz on what recursion is.

  1. A recursive function calls itself on a smaller piece of the same kind of input.
  2. The case a recursive function answers directly, without calling itself again, is the ___ case.
  3. Every recursive call must move closer to the base case, or the function never stops.
  4. Assuming the smaller recursive call already returns the right result is the leap of ___.
  5. A problem is a good fit for recursion when a smaller version of it looks like the whole problem.
  6. A set of nesting dolls, each holding a smaller copy, is one picture of ___.