File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Interview Prep/section19_DynamicProgramming Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ package section19_DynamicProgramming ;
2+
3+ public class CountBoardPathDP {
4+
5+ public static void main (String [] args ) {
6+
7+ int n = 10 ;
8+ System .out .println (countBoardPath (n , 0 , new int [n + 1 ])); // 492
9+ System .out .println (countBoardPathIterative (n )); // 492
10+ }
11+
12+ // O(N) Time - recursive storage
13+ public static int countBoardPath (int end , int current , int [] storage ) {
14+ if (current == end )
15+ return 1 ;
16+ if (current > end )
17+ return 0 ;
18+
19+ if (storage [current ] != 0 )
20+ return storage [current ];
21+
22+ int count = 0 ;
23+ for (int dice = 1 ; dice <= 6 ; dice ++) {
24+ count = count + countBoardPath (end , current + dice , storage );
25+ }
26+ storage [current ] = count ;
27+
28+ return count ;
29+ }
30+
31+ // iterative storage
32+ // O(6N) ~ O(N) Time | O(N) Space
33+ public static int countBoardPathIterative (int n ) {
34+ int [] storage = new int [n + 1 ];
35+
36+ // seed
37+ storage [n ] = 1 ;
38+
39+ for (int index = n - 1 ; index >= 0 ; index --) {
40+ int currSum = 0 ;
41+ for (int dice = index + 1 ; dice <= index + 6 && dice <= n ; dice ++) {
42+ currSum = currSum + storage [dice ];
43+ }
44+ storage [index ] = currSum ;
45+ }
46+
47+ return storage [0 ];
48+ }
49+ }
You canβt perform that action at this time.
0 commit comments