Staircase - Dynamic programming
Problem:
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.
Explanation:
Solution:
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.
Input: n = 1 Output: 1 There is only one way to climb 1 stair Input: n = 2 Output: 2 There are two ways: (1, 1) and (2) Input: n = 4 Output: 5 (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2)
Explanation:
-
What is the very last step that is done?
-
The very last hop the child makes- the one that lands her on the nth
step-was either a 3-step hop, a 2-step hop, or a 1-step hop.
-
How many ways then are there to get up to the nth step? We don't
know yet. but we can relate it to some subproblems.
-
If we thought about all of the paths to the nth step, we could just build
them off the paths to the three previous steps. We can get up to the nth step by any of the following:
-
Going to the (n - 1)st step and hopping 1 step.
-
Going to the (n - 2)nd step and hopping 2 steps.
-
Going to the (n - 3)rd step and hopping 3 steps.
Therefore, we just need to add the number of these paths together.
-
Going to the (n - 1)st step and hopping 1 step.
Solution:
class stairs { // A recursive function used by countWays static int countWaysUtil( int n, int m) { if (n <= 1 ) return n; int res = 0 ; for ( int i = 1 ; i<=m && i<=n; i++) res += countWaysUtil(n-i, m); return res; } // Returns number of ways to reach s'th stair static int countWays( int s, int m) { return countWaysUtil(s+ 1 , m); } /* Driver program to test above function */ public static void main (String args[]) { int s = 4 ,m = 2 ; System.out.println( "Number of ways = " + countWays(s,m)); } } |
Comments
Post a Comment