Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary.

Slides:



Advertisements
Similar presentations
Recursion.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
CSE Lecture 3 – Algorithms I
1 Exceptions – quick review Exceptions – quick review Recursion Recursion Power Function Power Function Towers of Hanoi Towers of Hanoi Fibonacci Numbers.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Standard Template Library Ming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion Gordon College CPS212
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Main Index Contents 11 Main Index Contents Selection Sort Selection SortSelection Sort Selection Sort (3 slides) Selection Sort Alg. Selection Sort Alg.Selection.
Chapter 8 Arrays and Strings
Data Structures Using C++1 Chapter 6 Recursion. Data Structures Using C++2 Chapter Objectives Learn about recursive definitions Explore the base case.
Fibonacci numbers Fibonacci numbers:Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... where each number is the sum of the preceding two. Recursive.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 Chapter 1 RECURSION. 2 Chapter 1  Subprogram implementation  Recursion  Designing Recursive Algorithms  Towers of Hanoi  Backtracking  Eight Queens.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Data Structures Using C++1 Chapter 6 Recursion. Data Structures Using C++2 Chapter Objectives Learn about recursive definitions Explore the base case.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Department of Computer Science Data Structures Using C++ 2E Chapter 6: Recursion Learn about recursive Definitions Algorithms Functions Explore the base.
1 Sorting Algorithms (Basic) Search Algorithms BinaryInterpolation Big-O Notation Complexity Sorting, Searching, Recursion Intro to Algorithms Selection.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 29 Assorted.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
1 CS 132 Spring 2008 Chapter 6 Recursion Read p Skip example 6-3 (Fibonacci), 6-4 (Hanoi) Read example 6-5 (p. 387)
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Chapter 8 Arrays and Strings
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Main Index Contents 11 Main Index Contents Building a Ruler: drawRuler() Building a Ruler: drawRuler() Merge Algorithm Example (4 slides) Merge Algorithm.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Data Structures Using Java1 Chapter 5 Recursion. Data Structures Using Java2 Chapter Objectives Learn about recursive definitions Explore the base case.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Recursion.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursion.
Chapter 15 Recursion.
Chapter 17 Recursion.
Chapter 15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Algorithm Analysis (for Divide-and-Conquer problems)
Chapter 12 Recursion (methods calling themselves)
Algorithm design and Analysis
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary Chapter 3 Templates Recursion Basics Power Function Recursive Defn Recursive Function Towers of Hanoi Fibonacci Numbers Summary

Main Index Contents 22 Main Index Contents Selection Sort Algorithm Integer Version void selectionSort (int arr[], int n) {... int temp; // used for the exchange for (pass = 0; pass < n-1; pass++) {... // compare integer elements if (arr[j] < arr[smallIndex])... }

Main Index Contents 33 Main Index Contents Selection Sort Algorithm String Version void selectionSort (string arr[], int n) {... string temp; //used for the exchange for (pass = 0; pass < n-1; pass++) {... // compare string elements if (arr[j] < arr[smallIndex])... }

Main Index Contents 4 Template Syntax template function syntax includes the keyword template followed by a non-empty list of formal types enclosed in angle brackets. In the argument list, each type is preceded by the keyword typename, and types are separated by commas. // argument list with a multiple template // types template

Main Index Contents 5 Template Syntax Example template void selectionSort (T arr[], int n) { for (int pass = 0; pass < n-1; pass++) { // scan unsorted sublist to find smallest value int smallIndex = pass; for (int j = pass+1; j < n; j++) if (arr[j] < arr[smallIndex]) smallIndex = j; // swap smallest value with leftmost if (smallIndex != pass) { T temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; }

Main Index Contents 6 Template Function Instantiation The compiler does not create the executable code for a template function until it encounters a call to it The actual parameter type(s) in the call determine the template type T, and a version of the function is create for that actual type int A[10]; selectionSort( A, 10); // int array String S[50]; selectionSort( S, 50); // string array

Main Index Contents 7 Recursive Algorithms Use a recursive function to implement a recursive algorithm. The recursive function must consists of … 1.One or more stopping conditions (base cases) that can be directly evaluated for certain arguments. 2.One or more recursive steps in which a current value of the function can be computed by calling the function with arguments that will eventually arrive at a stopping condition.

Main Index Contents 88 Main Index Contents Recursive Definition of the Power Function A recursive definition of x n distinguishes between … n = 0 (starting point) where x n = x 0 = 1 and n  1 where x n can be calculated using the calculated value of x n-1

Main Index Contents 99 Main Index Contents Implementing the Recursive Power Function double power(double x, int n) // pre: n is non-negative { if (n == 0) // base case return 1.0; else // recursive step return x * power(x,n-1); }

Main Index Contents 10 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion

Main Index Contents 11 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion

Main Index Contents 12 Towers of Hanoi void hanoi (int n, char src, char dest, char spare) { if (n > 1) { hanoi(n-1,src,spare,dest); cout << “move ” << src << “ to ” << dest << ‘\n’; hanoi(n-1,spare,dest,src); } else // last disk (n == 1) cout << “move ” << src << “ to ” << dest << ‘\n’; }

Main Index Contents 13 Fibonacci Numbers (Recursive solution) int fib (int n) { if ((n == 0) || (n == 1)) // base cases return 1; else // general case // (sum of previous two values) return (fib(n-1) + fib(n-2)); } The sequence of Fibonacci numbers. {1, 1, 2, 3, 5, 8, 13, 21, 34,...}

Main Index Contents 14 Recursive calls for fib(5)

Main Index Contents 15 Fibonacci with dynamic programming int fibDyn (int n vector & fibList) { // pre: fibList contains all -1 values int fibValue; if(fibList[n] >= 0) // previously computed return fibList[n]; if (n <= 1) // base cases (0 & 1) fibValue = 1; else fibValue = fibDyn(n-1,fibList) + fibDyn(n-2,fibList); fibList[n] = fibValue; // save value in fibList return fibValue; }

Main Index Contents 16 Main Index Contents Affect of fib(5) Using Dynamic Programming

Main Index Contents 17 Fibonacci Numbers using Iteration int fibiter (int n) { int oneback = 1, twoback = 1, current; if (n == 0 || n == 1) // base cases return 1; else // compute successive terms for (int i = 3; i <= n; i++) { current = oneback + twoback; twoback = oneback; oneback = current; } return current; }

Main Index Contents 18 Permutations Recursive Approach Permutations of a list of n values include all possible re-orderings of those values The number of permutations is n! We will use a vector (permList) to hold the values At each level of recursion (i), we create n-i recursive calls Prior to each recursive call permList[i] is swapped with permList[j], for all i < j < n

Main Index Contents 19 Permutations void permute (vector permList, int index) { // permList must be value parameter int vSize = permList.size(); if (index == vsize-1) writeList(permList); // show result else { for (int i =index+1; i<vSize; i++) { int temp = permList[index]; permList[index] = perList[i]; permList[i] = temp; // shuffle positions index+1.. vsize-1 permute(permList, index+1) }

Main Index Contents 20 The 8-Queens Example

Main Index Contents 21 Main Index Contents The 8-Queens Example (Cont…)

Main Index Contents 22 Eight Queens bool placeQ (vector & qList, int col) { bool found = false; if (col == 8) found = true; // all 8 queens placed else { int row = 0; while (row < 8 && !found) // place queen in column { if (safeLoc(row,col,qlist)) { qList[col] = row; // place queen on row found = placeQ(qList,col+1); // place the rest? if (!found) row++; // try next row this column } else row++; // not safe, move queen to next row } return found; // found complete solution? }

Main Index Contents 23 Eight Queens bool queens (vector & qList, int row) { qList[0] = row; // start at board[row,0] return placeQ(qList,1); // continue in column 1 } bool safeLoc (int row, int col, const vector & qList) { for (int qCol = 0; qCol < col; qCol++) { int qRow = qList[qCol]; if ((qRow == row) || (qCol-qRow == col-row) || (qCol+qRow == col+row) ) return false; // on same row or diagonal } return true; // safe, not under attack }

Main Index Contents 24 Main Index Contents Summary Slide 1 §- C++ provides a template mechanism that allows a programmer to write a single version of a function with general type arguments. -If a main program wants to call the function several times with different runtime arguments, the compiler looks at the types of the runtime arguments and creates different versions of the function that matches the types.

Main Index Contents 25 Main Index Contents Summary Slide 2 §- An algorithm is recursive if it calls itself for smaller problems of its own type. §-Eventually, these problems must lead to one or more stopping conditions. -The solution at a stopping condition leads to the solution of previous problems. -In the implementation of recursion by a C++ function, the function calls itself.

Main Index Contents 26 Main Index Contents Summary Slide 3 §- Dynamic Programming (top down) 1) Fibonacci function - uses a vector to store Fibonacci numbers as a recursive function computes them - avoids redundant recursive calls and leads to an O(n) algorithm to find the n th Fibonacci number. - recursive function that does not apply dynamic programming has exponential running time.

Main Index Contents 27 Main Index Contents Summary Slide 4 §- Backtracking Algorithm (8 Queens) - find a consistent partial solution (place a queen safely in current column) -try to recursively extend the partial solution to a complete solution (place queen in next column …) -If recursive step fails to find a complete solution, it returns and the algorithm tries again from a new consistent partial solution. (replace queen in current column & continue, or return to previous column if necessary)