Docsity

Recursion and Backtracking: Solving Problems with Recursive Algorithms in Data Structures, Lecture notes of Data Structures and Algorithms

Partial preview of the text

Download Recursion and Backtracking: Solving Problems with Recursive Algorithms in Data Structures and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and

Algorithms

LECTURE 03: RECURSION AND BACKTRACKING

• Recursion

• Generating Simple Combinations

• Backtracking

  • The 8 Queens Problem
  • Finding All Paths in a Labyrinth Recursively

• Recursion or Iteration?

  • Harmful Recursion and Optimizing Bad Recursion

Contents

• What is Recursion?

  • A function or a method that calls itself one or more times until a specified condition is met
  • After the recursive call the rest code is processed from the last one called to the first.

Recursion

• "The stack" is a small fixed-size chunk of memory (e.g.

1MB)

• Keeps track of the point to which each active subroutine

should return control when it finishes executing

Call Stack

Call Stack call Main Method A Method B call return return

Array Sum – Example

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

• Create a recursive method that

  • Finds the sum of all numbers stored in an int[] array
  • Read numbers from the console

Problem: Array Sum

  • Create a recursive method that calculates n!
    • Read n from the console

Problem: Recursive

Factorial

  • Recursive definition of n! (n factorial):

Recursive Factorial –

Example

n! = n * (n–1)! for n > 0 0! = 1 3! 3 * 2! 2! 2 * 1! 1! 1 * 0! 0! 1

  • Direct recursion
    • A method directly calls itself
  • Indirect recursion
    • Method A calls B , method B calls A
    • Or even ABCA

Direct and Indirect

Recursion

 Recursive methods have three parts:

Pre-actions (before calling the recursion)  Recursive calls (step-in)  Post-actions (after returning from recursion)

Recursion Pre-Actions and

Post-Actions

static void recursion() { // Pre-actions recursion(); // Post-actions }

  • Sample source code

Pre-Actions and Post-

Actions – Example

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 }

• Generating Simple Combinations

Recursive Algorithm

  • Start with a blank vector
  • Choose the first position and loop through all possibilities
  • For each possibility, generate all (n – 1)-bit vectors

Generating 0/1 Vectors

n - 1 n^ -^1 0 … … … … … … … 0 … … … … … … … 1 … … … … … … …

Solution: Generate n-bit

Vectors

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); } } }