Upload
haseeb-qureshi
View
496
Download
0
Embed Size (px)
Citation preview
You can easily express factorial in terms of subproblems.
Specifically, if you have the subproblem
(N - 1)! you can easily get
N!
N * (N - 1)!
First, we need to know how to solve the problem of size N in terms of smaller subproblems.
This is also called the inductive step.
(See: induction)
0! = 1 Second, we need the base case.
The recursion has to end somewhere, so we just hard-code it in.
WORDS OF WARNING
▸ Recursion is often weird and unintuitive.
▸ Don’t try to do something recursively that’s better done iteratively!
▸ But there are times when it’s the most elegant way to solve a problem.
▸ E.g., factorial, sorting, many tree and graph problems (or generally when using any recursive data structure).
DEBUGGING RECURSION
▸ Recursion is usually more difficult to debug.
▸ If you don’t define your base case properly, you’ll usually trigger a stack overflow.
DEBUGGING RECURSION
▸ Console.log is your friend.
▸ Recursion usually works not at all, or everything works at once. This makes it trickier to introspect.
▸ Consider using: if (condition) debugger;
MORE RECURSION ADVICE
▸ Start with the inductive step.
▸ Don’t go straight into coding it, first map it out and make sure you understand it.
▸ Then enter in the base case.
▸ Usually if you’re hard-coding multiple base cases, you’re overcomplicating it.
TIPS ON GENERATING THE INDUCTIVE STEP
▸ First, think about what a subproblem would look like. How can I make the input smaller?
▸ Is it size N - 1? N - 3? N / 2? All of these are valid subproblem sizes; what would make the solution easy?
▸ Think of recursion like cheating…
fn:one line 17LocalVariables
THE STACK:fn:two line 22Local
Variables
fn:three line 27LocalVariables
>> Finished function 3.
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
THE STACK:
fn:one line 17LocalVariables
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
THE STACK:
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
THE STACK:
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
THE STACK:
fn:one line 17LocalVariables
fn:two line 22LocalVariables
fn:three line 28LocalVariables
fn:one line 17LocalVariables
SO IF YOU WANT TO IMPLEMENT A RECURSIVE ALGORITHM
ITERATIVELY, YOU OFTEN NEED TO MANAGE YOUR OWN STACK.
IT GETS MORE COMPLICATED THAN THAT, BUT THAT’S A GOOD STARTING POINT.(SEE MASTER METHOD, RECURRENCES,
RECURSION TREES, ETC.)
I AM HASEEB QURESHI
You can find me on Twitter: @hosseeb
You can read my blog at: haseebq.com