Sunday 29 January 2017

Recursive solution to Total number of sequences : C Program with Memoization

Write a recursive function to Find the total number of sequences of length n (using H and T) such that no two Hs are next to each other.

#include <stdio.h>
int a[20];
int total_seq(int n)
{
if(n == 1)
return 2;
if(n ==2)
return 3;
if(a[n]!=-1 )
return a[n];
a[n]=total_seq(n-1)+total_seq(n-2);
return a[n];
}
main()
{
int n,i;
printf("enter n value");
scanf("%d",&n);
for(i=0;i<20;i++)
a[i]=-1;
printf("\n Total number of sequences = %d",total_seq(n));
}


No comments:

Post a Comment