LintCode 20. 骰子求和

扔 n 个骰子,向上面的数字之和为 S。给定 Given n,请列出所有可能的 S 值及其相应的概率。


public class Solution {
    /**
     * @param n an integer
     * @return a list of Map.Entry<sum, probability>
     */
    public List<Map.Entry<Integer, Double>> dicesSum(int n) {
        // Write your code here
        // Ps. new AbstractMap.SimpleEntry<Integer, Double>(sum, pro)
        // to create the pair
        long[][] dp = new long[n+1][6*n+1];
        dp[1][1] = 1;
        dp[1][2] = 1;
        dp[1][3] = 1;
        dp[1][4] = 1;
        dp[1][5] = 1;
        dp[1][6] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = i; j <= 6*i; j++) {
                long x1=0, x2=0, x3=0, x4=0, x5=0, x6=0;
                if (j - 1 > 0) {
                    x1 = dp[i-1][j-1];
                }
                if (j - 2 > 0) {
                    x2 = dp[i-1][j-2];
                }
                if (j - 3 > 0) {
                    x3 = dp[i-1][j-3];
                }
                if (j - 4 > 0) {
                    x4 = dp[i-1][j-4];
                }
                if (j - 5 > 0) {
                    x5 = dp[i-1][j-5];
                }
                if (j - 6 > 0) {
                    x6 = dp[i-1][j-6];
                }
                dp[i][j] = x1 + x2 + x3 + x4 + x5 + x6;
            }
        }
        List<Map.Entry<Integer, Double>> list = new ArrayList<>();
        for (int i = n; i <= n*6; i++) {
            AbstractMap.SimpleEntry<Integer, Double> entry = new AbstractMap.SimpleEntry<>(i, dp[n][i]/Math.pow(6, n));
            list.add(entry);
        }
        return list;
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页