




























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























LECTURE 03: RECURSION AND BACKTRACKING
Call Stack call Main Method A Method B call return return
Sum(n) Sum(n^ -^ 1) Sum((n – 1) - 1) Sum(((n – 1) - 1) – 1) 1 2 3 4 1 3 4 2 3 4 1 2 1 2 3 4
n! = n * (n–1)! for n > 0 0! = 1 3! 3 * 2! 2! 2 * 1! 1! 1 * 0! 0! 1
Pre-actions (before calling the recursion) Recursive calls (step-in) Post-actions (after returning from recursion)
static void recursion() { // Pre-actions recursion(); // Post-actions }
Base case Recursive call static void printFigure(int n) { if (n == 0) { return; } // TODO: Pre-action: print n asterisks printFigure(n - 1); // TODO: Post-action: print n hashtags }
n - 1 n^ -^1 0 … … … … … … … 0 … … … … … … … 1 … … … … … … …
Base case Recursive call static void gen01(int index, int[] vector) { if (index >= vector.length()) { print(vector); } else { for (int i = 0; i <= 1; i++) { vector[index] = i; gen01(index + 1, vector); } } }