Tutorials, Free Online Tutorials,It Challengers provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, core java, sql, php, c language etc. for beginners and professionals.

Breaking

Count ways to reach the n'th stair

Q.)Count ways to reach the n'th stair. There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top.





Answer:-
It's a dynamic programming problem.
A child can climb to stair N from stair N - 1, or stair N - 2, or stair N -3.
The the ways to climb to N is adding up all the ways to N - 1, N - 2 and N - 3.
So:
 f(n) = f(n - 1) + f(n - 2) + f(n - 3)
While for first three stairs:
f(1) = 1;
f(2) = 1 + f(1)
f(3) = 1 + f(2) + f(1).

In C-like codes:
sol[1] = 1; 
sol[2] = 2; //1 + sol[1];
sol[3] = 4; // 1 + sol[2] + sol[1]
for(int i = 4; i <= N; i++) 
    sol[i] = sol[i - 1] + sol[i - 2] + sol[i - 3];

Then sol[N] will be the answer.

No comments:

Post a Comment