Recursion

Any questions before we start?

Recursion Basics

Recursion

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.

 

Example

we can define the operation "Go to Home" as:

 

Base Case

1.  If you are at home, stop moving.

 

Recursive Case

2. Take one step toward home.

3. "Go To Home".

Code

Text


//A Simple Recursive Function 
static void goHome(x,Home){

  if(x == Home){
      print("Reached Home")
      return;
  }

  x = x + 1
  goHome(x,Home) 
}


//Main
int x = 1
int Home = 10
goHome(x,Home);

Recursion  = Principal of Mathematical Induction

1. Figure of the Smallest Case

 

2. Always Assume the Subproblem Can be Solved


3. Solve the current problem assuming subproblem solution exists

Factorial of Number

Input

5

 

Output

120

Call Stack! 👨‍💻

Time & Space Utilisation 👨‍💻

Fibonacci Number

Write a program to compute the nth Fibonacci Number.
Fibonacci Series:

0, 1, 1, 2, 3, 5, 8 , ........

Increasing Numbers

Given N, print numbers from 1 to N without using a Loop (Use Recursion)

 

Input

5

 

Output

1, 2, 3, 4, 5

 

Decreasing Numbers

Given N, print numbers from 1 to N without using a Loop (Use Recursion)

 

Input

5

 

Output

5, 4, 3, 2, 1

Sum the Digits

Given N, print the sum of digits of that number using recursion.

 

Input

512

 

Output

8

More Problems

Climbing Ladder

Given a ladder containing N Steps, you can take a jump of 1,2 or 3 at each step. Find the number of ways to climb the ladder.

Sample Input

N = 4

Sample Output

7

Tiling Problem

Given Given a “4 x n” board and tiles of size “4 x 1”, count the number of ways to tile the given board using the 4 x 1 tiles.

 

A tile can either be placed horizontally i.e., as a 1 x 4 tile or vertically i.e., as 4 x 1 tile.

Input

N

 

Output

No of ways

Binary Strings

Count the number of binary strings with no consecutive ones that can be formed using a binary string of Length N.

Input

N

 

Output

Count of Strings

Friend's Pairing Problem

Given n friends who want to go to party, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. 

Examples: 

Made with Slides.com