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.


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. 

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

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string