【劍指offer-Java版】43n個骰子的點數
阿新 • • 發佈:2019-02-12
屬於比較適合進行時空權衡的題目,不過沒有過多的研究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);
}
}
}