We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 7676443 commit d79b0a5Copy full SHA for d79b0a5
1 file changed
src/test/java/algorithm/dp/FiboByDp.java
@@ -0,0 +1,33 @@
1
+package algorithm.dp;
2
+
3
+import org.junit.Test;
4
5
+import static org.hamcrest.CoreMatchers.is;
6
+import static org.junit.Assert.assertThat;
7
8
+public class FiboByDp {
9
+ @Test
10
+ public void test() {
11
+ assertThat(5, is(fiboByDp(5)));
12
+ assertThat(8, is(fiboByDp(6)));
13
+ assertThat(13, is(fiboByDp(7)));
14
+ }
15
16
+ public int fiboByDp(int num) {
17
+ return calcFibo(num, new int[num + 1]);
18
19
20
+ private int calcFibo(int num, int[] cache) {
21
+ if (num < 2) {
22
+ return num;
23
24
25
+ //in java, int[] is initialized by 0.
26
+ if (cache[num] != 0) {
27
+ return cache[num];
28
29
30
+ cache[num] = calcFibo(num - 1, cache) + calcFibo(num - 2, cache);
31
32
33
+}
0 commit comments