Skip to content

Commit e60b1dc

Browse files
author
turingfly
committed
Recursion and Dynamic Programming
1 parent f2f0e1b commit e60b1dc

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package chapter08RecursionAndDynamicProgramming;
2+
3+
/**
4+
*
5+
* Problem:
6+
*
7+
*/
8+
public class RobotInAGrid {
9+
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package chapter08RecursionAndDynamicProgramming;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
*
7+
* Problem: A child is running up a staircase with n steps and can hop either 1
8+
* step, 2 steps, or 3 steps at a time. Implement a method to count how many
9+
* possible ways the child can run up the stairs.
10+
*
11+
*/
12+
public class TripleSteps {
13+
/**
14+
* Method 1: Brute Force Recursion
15+
*
16+
* Time Complexity: O(3N)
17+
*/
18+
public int countWays1(int n) {
19+
if (n < 0) {
20+
return 0;
21+
} else if (n == 0) {
22+
return 1;
23+
} else {
24+
return countWays1(n - 1) + countWays1(n - 2) + countWays1(n - 3);
25+
}
26+
}
27+
28+
/**
29+
* Method 1: Brute Force Recursion. Number of ways will quickly overflow the
30+
* bounds of an integer. n = 37; Time Complexity: O(N)
31+
*/
32+
public int countWays2(int n) {
33+
int[] memo = new int[n + 1];
34+
Arrays.fill(memo, -1);
35+
return countWays2(n, memo);
36+
}
37+
38+
private int countWays2(int n, int[] memo) {
39+
if (n < 0) {
40+
return 0;
41+
} else if (n == 0) {
42+
return 1;
43+
} else if (memo[n] > -1) {
44+
return memo[n];
45+
} else {
46+
memo[n] = countWays2(n - 1, memo) + countWays2(n - 2, memo) + countWays2(n - 3, memo);
47+
return memo[n];
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)