属于比较适合进行时空权衡的题目,不过没有过多的研究dp技巧,只是简单的用作者的思路实现了下
public class _Q43<T> {
private final static int dice = 6; // 面数
public static void main(String[] args) {
PrintDiceProb(2);
}
// 直接采用作者的思路,使用了一个开关数组实现
public static void PrintDiceProb(int n) {
if (n < 1)
return;
int togger = 0;
int[][] probs = new int[2][];
probs[0] = new int[dice * n + 1];
probs[1] = new int[dice * n + 1];
for (int i = 1; i <= dice; i++) {
probs[togger][i] = 1;
}
for (int k = 2; k <= n; k++) {
for (int i = k; i <= k * dice; i++) {
probs[1 - togger][i] = 0;
for (int j = 1; j <= i && j <= dice; j++) {
probs[1 - togger][i] += probs[togger][i - j];
}
}
togger = 1 - togger;
}
long total = (long) Math.pow(dice, n);
for (int i = n; i <= dice * n; i++) {
double ratio = (double) probs[togger][i] / total;
System.out.println(i + " --> " + ratio);
}
}
}