Recursion

Just like inception

Tail recursion

The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.

We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n).

long fact(int n){
   if(n <= 1)
      return 1;
   n * fact(n-1);
}

We can make it tail recursive, by adding some other parameters. This is like below −

long fact(long n, long a){
   if(n == 0)
      return a;
   return fact(n-1, a*n);
}

When last statement is recursion, it is tail recursion, which is optimized by compiler using goto statements.

1 to N and N to 1


class Solution {
    public static void main(String[] args) {
        System.out.println("--- start ---");

        print1ToN(9);
        System.out.println();
        printNTo1(9);

        System.out.println("\n--- end ---");
    }

    private static void printNTo1(int i) {
        if (i == 0) {
            return;
        }
        System.out.print(i + "|");
        printNTo1(i - 1);
    }

    private static void print1ToN(int i) {
        if (i == 0) {
            return;
        }
        print1ToN(i - 1);
        System.out.print(i + "|");
    }
}

Tower of Hanoi

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  1. Only one disk can be moved at a time.

  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.

  3. No disk may be placed on top of a smaller disk.

Just remember : 132 | 123 | 231

Fibonacci (Recursion)

Count Total Digits

Sum of Digits

Is string palindrome

Josephus problem

Power Using Recursion

Digital Root

Sum of all digits ,, till a single digit is achieved

ex : 99999 -> 45 -> 9

Sum of digit of a number

using recursion

Rod cutting

Important : Inputs should be sort

All subsets of string

All permutation of String

Last updated