-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountBoardPathDP1.java
More file actions
97 lines (64 loc) · 2.19 KB
/
Copy pathCountBoardPathDP1.java
File metadata and controls
97 lines (64 loc) · 2.19 KB
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
93
94
95
package codingInterview.Recursion;
public class CountBoardPathDP1 {
public static int countBoardPath(int s, int d, String asf) {
int cstod = 0;
if (s > d) return 0;
if (s == d) return 1;//Don't throw the dice
for (int dice = 1; dice <= 6; dice++) {
int intermediate = s + dice;
int c = countBoardPath(intermediate, d, asf + dice);
cstod += c;
}
return cstod;
}
//T(n)=T(n-1)...<=k+6T(n-1)
// T(n)= k+6k+6^2k...=k(6^n-1)/6-1=6^n
public static int countBoardPathMemo(int s, int d, int QuesBank[]) {
int cstod = 0;
if (s > d) return 0;
if (s == d) return 1;//Don't throw the dice
if (QuesBank[s] != 0) return QuesBank[s];
for (int dice = 1; dice <= 6; dice++) {
int intermediate = s + dice;
int c = countBoardPathMemo(intermediate, d, QuesBank);
cstod += c;
}
QuesBank[s] = cstod;
return cstod;
}
public static int countBoardPathTabular(int s, int d) {
//f(x)=CBP(x,d)
int Array[] = new int[d + 1];
Array[d] = 1;
for (int k = d - 1; k >= 0; k--) {
for (int dice = 1; dice <= 6; dice++) {
if (k + dice <= d)
Array[k] += Array[k + dice];
}
}
return Array[0];
}
public static int countBoardPathSlider(int s, int d) {
int Array[] = new int[6];
Array[0] = 1;//0==d
//S12345= concide with F11..15 if d=10
int temp = 0;
for (int k = d; k >= 1; k--) {
temp = Array[5] + Array[4] + Array[3] + Array[2] + Array[1] + Array[0];
Array[5] = Array[4];
Array[4] = Array[3];
Array[3] = Array[2];
Array[2] = Array[1];
Array[1] = Array[0];
Array[0] = temp;
}
return Array[0];
}
public static void main(String str[]) {
int n = 10;
System.out.println(countBoardPathSlider(0, n));
System.out.println(countBoardPathMemo(0, n, new int[n + 1]));//fast.
System.out.println(countBoardPathTabular(0, n));//working fine.
return;
}
}