Created
August 13, 2017 21:29
-
-
Save sdpatil/d5b395b53f07628fc7ae0d7dc32041b7 to your computer and use it in GitHub Desktop.
Count the number of moves to climb stair
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem: Given totalNumber of ways and how many steps you can take in one go calculate how many | |
ways you can climb to top | |
*/ | |
public class NumberOfWaysToClimbStairs { | |
public static void main(String[] argv) { | |
System.out.println(computeNumberOfWays(4, 3)); | |
} | |
/* | |
This is special case if you can only take 2 steps at the most then this becomes problem similar to | |
fibonacci series | |
*/ | |
public static int computeNumberOfWaysTwoStepsMax(int n) { | |
if (n == 0 || n == 1) | |
return 1; | |
return computeNumberOfWaysTwoStepsMax(n - 1) + computeNumberOfWaysTwoStepsMax(n - 2); | |
} | |
/* | |
This is more generic version which takes second argument on how many steps are you allowed to take | |
at a time | |
*/ | |
public static int computeNumberOfWays(int n, int maximumStep) { | |
return computeNumberOfWays(n, maximumStep, new int[n + 1]); | |
} | |
public static int computeNumberOfWays(int n, int maximumStep, int[] numberOfWaysToH) { | |
if (n <= 1) | |
return 1; | |
if (numberOfWaysToH[n] == 0) { | |
for (int i = 1; i <= maximumStep && n - i >= 0; i++) { | |
numberOfWaysToH[n] = numberOfWaysToH[n] + | |
computeNumberOfWays(n - i, maximumStep, numberOfWaysToH); | |
} | |
} | |
return numberOfWaysToH[n]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment