【劍指offer-Java版】43n個骰子的點數

屬於比較適合進行時空權衡的題目,不過沒有過多的研究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);
        }

    }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章