- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathBoardPath.java
92 lines (69 loc) Β· 1.93 KB
/
BoardPath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
packagesection19_DynamicProgramming;
publicclassBoardPath {
publicstaticvoidmain(String[] args) {
intn = 100000;
// int start = 0, end = n;
// System.out.println(boardPathRecursive(start, end)); // 492
// System.out.println(boardPathTopDown(start, end, new int[n]));
System.out.println(boardPathBottomUp(n));
System.out.println(boardPathBottomUpSpaceEfficient(n));
}
// O(6^n) Time | Space - recursion extra space
publicstaticintboardPathRecursive(intstart, intend) {
if (start == end) {
return1;
}
if (start > end) {
return0;
}
intcount = 0;
for (intdice = 1; dice <= 6; dice++) {
count += boardPathRecursive(start + dice, end);
}
returncount;
}
// O(N) Time | O(N) Space + recursion extra space
// for large N, this will throw Stack overflow exception
publicstaticintboardPathTopDown(intcurrent, intend, int[] storage) {
if (current == end) {
return1;
}
if (current > end) {
return0;
}
if (storage[current] != 0) {
returnstorage[current];
}
intcount = 0;
for (intdice = 1; dice <= 6; dice++) {
count += boardPathTopDown(current + dice, end, storage);
}
storage[current] = count;
returncount;
}
// O(N) Time | O(N) Space
publicstaticintboardPathBottomUp(intend) {
int[] storage = newint[end + 6];
storage[end] = 1;
for (intindex = end - 1; index >= 0; index--) {
storage[index] = storage[index + 1] + storage[index + 2] + storage[index + 3] + storage[index + 4]
+ storage[index + 5] + storage[index + 6];
}
returnstorage[0];
}
// O(N) Time | O(1) Space
publicstaticintboardPathBottomUpSpaceEfficient(intend) {
int[] storage = newint[6];
storage[0] = 1; // store
for (intslide = end - 1; slide >= 0; slide--) {
intsum = 0;
for (intidx = 5; idx > 0; idx--) {
sum += storage[idx];
storage[idx] = storage[idx - 1];
}
sum += storage[0];
storage[0] = sum;
}
returnstorage[0];
}
}