Created
August 8, 2014 04:27
-
-
Save WOLOHAHA/395e15478b8849410cb4 to your computer and use it in GitHub Desktop.
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 possible ways the child can run up the stairs.
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
package POJ; | |
public class Main{ | |
/** | |
* | |
* 9.1 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 possible ways the child can run up the stairs. | |
* | |
* | |
*/ | |
public static void main(String[] args) { | |
Main so = new Main(); | |
int stairCount = 3; | |
int[] map = new int[stairCount + 1]; | |
for (int i = 0; i < stairCount + 1; i++) { | |
map[i] = -1; | |
} | |
System.out.println(so.countWaysDP(stairCount, map)); | |
System.out.println(so.countWaysRecursive(stairCount)); | |
} | |
public int countWaysDP(int n, int[] map) { | |
if (n < 0) | |
return 0; | |
else if (n == 0) | |
return 1; | |
else if (map[n] > -1) | |
return map[n]; | |
else { | |
map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) | |
+ countWaysDP(n - 3, map); | |
return map[n]; | |
} | |
} | |
public int countWaysRecursive(int n) { | |
if (n < 0) | |
return 0; | |
else if (n == 0) | |
return 1; | |
else { | |
return countWaysRecursive(n - 1) + countWaysRecursive(n - 2) | |
+ countWaysRecursive(n - 3); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment