File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
src/test/java/algorithm/dp Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments