Created
February 15, 2013 23:33
-
-
Save charlespunk/4964489 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how | |
many posible ways the child can run up the stairs. |
This file contains hidden or 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
public static int countWays(int high){ | |
if(high == 0) return 1; | |
else if(high > 0) return (countWays(high - 1) + countWays(high - 2) + countWays(high - 3)); | |
else return 0; | |
} |
This file contains hidden or 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
public static void countWays(int high){ | |
if(high <= 0) return 0; | |
int[] dp = new int[high + 1]; | |
dp[0] = 1; | |
countWays(high, dp); | |
return dp[high]; | |
} | |
public static void countWays(int high, int[] dp){ | |
if(high < 0) return 0; | |
else if(dp[high] > 0) return dp[high]; | |
else{ | |
dp[high] = countWays(high - 1, dp) + countWays(high - 2, dp) + countWays(high - 3, dp); | |
return dp[high]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment