Amazon Interview Question
Country: India
public int CountWays(int N)
{
if(N<0) return 0;
else if(N==0) return 1;
else
{
return CountWays(N-1) + CountWays(N-2);
}
}
At each step, one can take either one step or two steps. A simple Dynamic programming approach can be used.
Below is the working C code for n==6:
#include<stdio.h>
#include<conio.h>
int main(int n)
{
int temp;
int hash[7]={0};
hash[0]=hash[1]=1;
temp=func(6,hash);
printf("%d",temp);
getch();
return 1;
}
int func(int n,int hash[])
{
if(hash[n]!=0)
return hash[n];
int ways;
ways=0;
ways+=func(n-2,hash);
ways+=func(n-1,hash);
hash[n]=ways;
return hash[n];
}
If you Search google you will find this answer also ..
- MI December 28, 2012F(n) to reach n steps ..
then F(n) = F(n-1) + F(n -2) [ you can reach n only from n-1 and n -2 level ]
F(1) = 1;
F(2) = 2;
But permutation and combination answer is also correct !!