lintcode 20 Dices Sum

题目描述

Description
Throw n dices, the sum of the dices’ faces is S. Given n, find the all possible value of S along with its probability.

  • You do not care about the accuracy of the result, we will help you to output results.

Example
Given n = 1, return [ [1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]].

思路

看到这题,首先想到的就是动态规划了,二维数组记录概率,然后用公式来求解:在这里插入图片描述
n是骰子数量,a是点数,f(n,a)指的是n个骰子点数为a的概率
有了公式就很方便进行求解了

  • 第一层循环,表示骰子数量
  • 第二层循环,表示点数
  • 第三层循环,用来计算概率

代码

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
        List<Map.Entry<Integer, Double>> result = new ArrayList<>();
        double[][] dp = new double[n + 1][n * 6 + 1];
        for (int i = 1; i < 7; i++) {
            dp[1][i] = 1.0 / 6;
        }
        for (int i = 2; i <= n; i++) {
            for (int j = i; j <= 6 * i; j++) {
                for (int m = 1; m <= 6; m++) {
                    if (j > m) {
                        dp[i][j] += dp[i - 1][j - m];
                    }
                }
                dp[i][j] /= 6.0;
            }
        }
        for (int i = n; i <= 6 * n; ++i) {
            result.add(new AbstractMap.SimpleEntry<>(i, dp[n][i]));
        }
        return result;
    }

猜你喜欢

转载自blog.csdn.net/qq_35464543/article/details/82933271