How to implement Fibonacci using topDown approach using C#?

CsharpServer Side ProgrammingProgramming

The Fibonacci sequence is a set of numbers that starts with a one or a zero, followed by a one, and proceeds based on the rule that each number (called a Fibonacci number) is equal to the sum of the preceding two numbers. The top-down approach focuses on breaking down a big problem into smaller and understandable chunks. Space complexity is O(N) because we are creating an extra array memory which is equal to the size of number.

Time complexity − O(N)

Space complexity − O(N)

Example

public class DynamicProgramming{
   public int fibonacciTopdownApproach(int n,int[] dpArr ){
      if(n==0 || n == 1){
         return n;
      }
      if(dpArr[n] != 0){
         return dpArr[n];
      }
      int res = fibonacciTopdownApproach(n - 1,dpArr) + fibonacciTopdownApproach(n - 2,dpArr);
      return dpArr[n] = res ;
   }
}

static void Main(string[] args){
   DynamicProgramming dp = new DynamicProgramming();
   int[] dpArr = new int[150];
   Console.WriteLine(dp.fibonacciTopdownApproach(12, dpArr));
}

Output

144
raja
Published on 17-Aug-2021 08:11:36
Advertisements