Skip to content

Commit d79b0a5

Browse files
committed
Add dynamic programming code
1 parent 7676443 commit d79b0a5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
return cache[num];
32+
}
33+
}

0 commit comments

Comments
 (0)